Top Banner
INTRODUCTION TO OOP Session 4
68
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to OOP

INTRODUCTION TO OOP

Session 4

Page 2: Introduction to OOP

A bit about me

Timisoara .Net Meetup organizer.

Web and mobile freelancer.

Xamarin enthusiast.

In love with software architecture.

@flaviusdemian

/pub/flavius-demian/32/191/178

/demian.flaviusradu

Page 3: Introduction to OOP

Agenda

What is OOP

OOP and .NET

Classes, objects, constructors

Encapsulation

Access Modifiers

The static keyword

Static vs Non-Static

Class inheritance

Page 4: Introduction to OOP

Agenda

Polymorphism

Method overloading

Method overriding

Abstract class

Sealed class

Interfaces

Interfaces vs abstract classes

Boxing and unboxing

The const keyword

Page 5: Introduction to OOP

Agenda

The readonly keyword

Properties

Indexers

The is and as keywords

Lists

Dictionaries

Queues

Stacks

Page 6: Introduction to OOP

What is OOP

Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which are data structures that contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.

In object-oriented programming, computer programs are designed by making them out of objects that interact with one another.

OOP is a methodology to write the program where we specify the code in form of classes and objects.

Page 7: Introduction to OOP

What is OOP

Page 8: Introduction to OOP

OOP and .NET

In .NET Framework the object-oriented approach has roots in the deepest architectural level.

All .NET applications are object-oriented.

All .NET languages are object-oriented.

There is no multiple inheritance in .NET.

Classes can implement several interfaces at the same time.

Every object inherits System.Object – the root of the hierarchy.

Page 9: Introduction to OOP

Classes, objects, constructors

Classes model real-world objected and define:

Attributes (state, properties, fields)

Behavior (methods, operations)

A class is a blueprint or a template while objects are usable instances of a class.

// class declaration

Class SampleClass {};

// object instantiation

SampleClass mySampleClass = new SampleClass();

Page 10: Introduction to OOP

Classes, objects, constructors

Constructors are used to create and initialize an object of a class.

A constructor resembles an instance method, but it differs from a method in that it has no explicit return type. Constructors have the same name as the declaring class.

They have the task of initializing the object's data members and fields.

class MyClass

{

public MyClass() { //code init here}

}

Page 11: Introduction to OOP

Encapsulation

It basically means hiding the internals of a class.

Encapsulation, in OOP, prevents access to implementation details.

It enables the programmer to implement the desired level of abstraction.

Encapsulation is implemented by using access modifiers, which define the scope and visibility of a class member.

Page 12: Introduction to OOP

Encapsulation

Page 13: Introduction to OOP

Access Modifiers

Class members can have access modifiers which:

are used to restrict the classes able to access them

support the OOP principle of encapsulation

provide a certain level of access

Access modifiers are:

public – accessible from any class

protected– accessible from the class itself and all its descendent classes

private – accessible from the class itself only

internal – accessible from the current assembly (used by default)

Page 14: Introduction to OOP

Access Modifiers

Demo

Page 15: Introduction to OOP

The static keyword

A static member of the class is a property, procedure, or a field that is shared by all instances of a class.

A static member is associated rather with a class than with a instance.

Static members cannot access non-static properties, fields or methods.

Page 16: Introduction to OOP

The static keyword

static class SampleClass

{

static string myString = “My static string”;

}

private static void Main(string[] args)

{

Console.Write(SampleClass.myString);

}

Page 17: Introduction to OOP

Static vs Non-Static

Static:

Associated with a type, not with an instance

Non-Static:

The opposite, associated with an instance

Static:

Initialized just before the type is used for the first time

Non-Static:

Initialized when the constructor is called

Page 18: Introduction to OOP

The static keyword

Demo

Page 19: Introduction to OOP

Class inheritance

Inheritance allows child classes to inherit the characteristics of existing parent class:

Attributes (fields and properties)

Operations (methods)

Child (derived) class can extend the parent class:

Add new fields and methods

Redefine methods (modify existing behavior)

Every class that extends the base class can replace the base class.

A derived class extends a base (parent) class.

A class can inherit only one class.

Page 20: Introduction to OOP

Class inheritance

In .NET you extend a class by using :

class DerivedClass : BaseClass

{

//code here

}

Inheritance has a lot of benefits:

Extensibility Provides abstraction

Reusability Eliminates redundancy

Page 21: Introduction to OOP

Class inheritance

Use inheritance for building IS A relationship.

A dog is an animal

Don’t use it to build HAS A relationship.

A dog has a name (dog is not kind of name)

Page 22: Introduction to OOP

Class inheritance

Inheritance is a transitive relation: Honda Shine also inherits Automobiles !

Page 23: Introduction to OOP

Class inheritance

Demo 3,4

Page 24: Introduction to OOP

Polymorphism

Polymorphism => poly = many, morph = shape => multiple shapes.

Objects can behave differently depending on their types => an operation may exhibit different behavior in different situations.

Base classes may define and implement virtual methods and derived

classes can override them.

Page 25: Introduction to OOP

Polymorphism

The signature of a method is its name and parameter list, not the return type.

It happens in 2 ways:

overriding methods in derived classes - dynamic polymorphism

overloading methods by changing the signature - static polymorphism

Page 26: Introduction to OOP

Overloading

Overloading is the ability to create multiple methods of the same name with different implementations.

Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call.

This allows one function call to perform different tasks depending on context.

For example, doTask() and doTask(string s) are overloaded methods.

Page 27: Introduction to OOP

Overloading

Demo

Page 28: Introduction to OOP

Overriding

By default, a derived class inherits all members from its base class.

Overriding is all about specialization and refinement.

A method is said to be a virtual one when it is declared as virtual.

public virtual void Calculate() { //code here };

Page 29: Introduction to OOP

Overriding

Methods that are declared as virtual in a base class can be overridden using the keyword override in the derived class.

You cannot override a non-virtual or static method.

The overridden base method must be virtual, abstract or override.

Page 30: Introduction to OOP

Overriding

Page 31: Introduction to OOP

Overriding

Demo

Page 32: Introduction to OOP

Polymorphism

Page 33: Introduction to OOP

Polymorphism

Page 34: Introduction to OOP

Abstract class

An abstract method is a method without implementation => it is left empty to be implemented by descendant classes.

When a class contains at least one abstract method, it is called an abstract class.

The derived classes are obliged to implement their abstract methods.

Abstract classes cannot be directly instantiated.

Page 35: Introduction to OOP

Abstract class

public abstract class MyAbstractClass

{

public abstract void DoWork();

}

public class RealClass : MyAbstractClass

{

public override void DoWork()

{

// code here

}

}

Page 36: Introduction to OOP

Abstract class

Demo

Page 37: Introduction to OOP

Sealed class

When applied to a class, the sealed modifier prevents other classes from extending it.

When you define new methods or properties in a class, you can prevent deriving classes from overriding them by not declaring them as virtual.

Page 38: Introduction to OOP

Sealed class

public abstract class MyAbstractClass

{

public abstract void DoWork();

}

public sealed class RealClass : MyAbstractClass

{

//it seals the implementation

public override sealed void DoWork()

{

// code here

}

}

Page 39: Introduction to OOP

Sealed class

public sealed class MySealedClass

{

//methods here

}

//This is not valid…You receive an error at compile-time.

public sealed class RealClass : MySealedClass

{

}

Page 40: Introduction to OOP

Sealed class

Demo

Page 41: Introduction to OOP

Interface

Interfaces, like classes, define a set of properties, methods and events.

But unlike classes, interfaces do not provide implementation.

They are implemented by classes and defined as separate entities from classes.

Page 42: Introduction to OOP

Interface

An interface represents a contract, meaning that a class that implements an interface must respect every aspect of that interface exactly as defined.

Cannot be instantiated. Members do not have scope modifier and by default the scope is public.

Page 43: Introduction to OOP

Interface

To define an interface:

Interface ISampleInterface

{

void doSomething();

}

To implement and interface in a class:

class SampleClass : ISampleInterface

{

void doSomething()

{ // code here }

}

Page 44: Introduction to OOP

Interface

Demo

Page 45: Introduction to OOP

Interfaces vs abstract classes

Interfaces and abstract classes allow you to create definitions for component interaction.

Through interfaces, you can specify methods that a component must implement without actually specifying how the method is implemented.

Abstract classes allow you to create definitions for behavior while providing some common implementation for inheriting classes.

Both are valuable tools for implementing polymorphic behavior in your components.

Page 46: Introduction to OOP

Boxing and unboxing

Boxing:

Cast a value-type instance to a reference-type instance:

int valueInteger = 9;

Object obj = valueInteger;

Unboxing:

Reverse – cast a reference-type instance to a value-type instance

int newValueInteger = (int)obj;

It is computationally expensive – best if avoided

Page 47: Introduction to OOP

The const keyword

Constant fields are defined like fields.

They are defined with the keyword const.

Constants must be initialized at their definition.

Their value cannot be changed at runtime.

public class MathConstants

{

public const double PI = 3.14159;

}

Page 48: Introduction to OOP

The readonly keyword

Read-only fields are initialized at the definition or in the constructor and cannot be modified further.

They are defined with the keyword readonly and represent runtime constants.

public class ReadOnlyDemo

{

private readonly int size;

public ReadOnlyDemo(int size)

{

this.size = size;

}

}

Page 49: Introduction to OOP

Properties

Properties object’s are data to the outside world.

They control how the data is manipulated.

They can be

read-only

write-only

read and write

Properties give good level of abstraction.

Makes writing code easier .

Page 50: Introduction to OOP

Properties

Properties should have:

access modifier (public, protected, internal, private)

return type

unique name

Get and/or Set part

The getter and/or setter can contain code processing data in specific way.

Page 51: Introduction to OOP

Properties

public class Point

{

private int xCoord;

private int yCoord;

public int XCoord

{

get { return xCoord; }

set { xCoord = value; }

}

public int Ycoord

{

get { return yCoord; }

set { yCoord = value; }

}

}

Page 52: Introduction to OOP

Properties

Properties are not obligatory bound to a class field – they can be calculated dynamically => dynamic properties.

public class Rectangle

{

private float width;

private float height;

public float Area

{

get

{

return width * height;

}}

}

Page 53: Introduction to OOP

Properties

Demo

Page 54: Introduction to OOP

Indexers

Indexers provide access to inner list/dictionary of values.

public class Zoo{

public Animal[] animals;

public Zoo(Animal[] animals){

this.animals = animals;}public Animal this [int animalIndex]{

get { return animals[animalIndex]; }set { animals[animalIndex] = value; }

}}

Page 55: Introduction to OOP

Indexers

In the main method we would have something like this:

Zoo zoo = new Zoo( new Animal[]

{

new Animal(“Pete”),

new Animal(“Frank”),

new Animal(“Stephan”)

}

);

Console.WriteLine(zoo[2]);

Page 56: Introduction to OOP

Indexers

Demo

Page 57: Introduction to OOP

The is and as keywords

The is operator returns true if an object is an instance of a type.

The as operator attempts to cast to a specified type.

If it fails it returns null and it does not raise an exception.

var d = new Dog(“Rex”);

bool dogIsAnimal = d is Animal;

if( dogIsAnimal == true)

{

Animal dogAsAnimal = d as Animal;

}

Page 58: Introduction to OOP

The is and as keywords

Demo

Page 59: Introduction to OOP

List

The List class is a collection and defined in the System.Collections.Generic namespace.

It provides the methods and properties like other Collection classes such as add, insert, remove, search etc.

List<int> list = new List<int>();

list.Add(2);

list.Add(3);

foreach (int number in list) // Loop through List with foreach

{

Console.WriteLine(number );

}

Page 60: Introduction to OOP

List

Demo

Page 61: Introduction to OOP

Dictionary

A dictionary class is a data structure that represents a collection of keys and values pair of data.

The key is identical in a key-value pair and it can have at most one value in the dictionary, but a value can be associated with many different keys.

This class is defined in the System.Collections.Generic namespace.

Dictionary<string, int> dict = new Dictionary<string, int>();

dict.Add("one", 1);

dict.Add("two", 2);

Page 62: Introduction to OOP

Dictionary

foreach (KeyValuePair<string, int> pair in dict) // iterate over values

{

Console.WriteLine(pair.Key.ToString ()+ " - " + pair.Value.ToString () );

}

if (dict.ContainsKey("four") == true) //search for a key

{

Console.WriteLine(dict["four"].ToString ());

}

Page 63: Introduction to OOP

Dictionary

Demo

Page 64: Introduction to OOP

Queue

Queue is a FIFO (first in first out) collection. It processes elements in a first-in, first-out order.

To restate, it handles the elements that it received longest ago first.

// New Queue of integers

Queue<int> q = new Queue<int>();

q.Enqueue(5); // Add 5 to the end of the Queue.

q.Enqueue(10); // Then add 10. 5 is at the start.

Methods: Clear, Contains, Dequeue, Enqueue ,Peek, Count, ToArray,

Page 65: Introduction to OOP

Queue

Demo

Page 66: Introduction to OOP

Stack

Stack is a LIFO collection. It provides a powerful and simple last-in-first-out data structure.

This can help you develop parsers quickly and also replace complex recursive algorithms. Stack is a generic type.

Stack<int> stack = new Stack<int>();

stack.Push(100); - adds a value

stack.Push(1000); - adds a value

stack.Pop(); - removes 1000 and returns it

Methods: Push, Pop, Clear, Count, Copy, Search

Page 67: Introduction to OOP

Stack

Demo

Page 68: Introduction to OOP

References

Documentation:

http://msdn.microsoft.com/en-us

http://www.dotnetperls.com/

csharp.net-informations.com/

Presentations:

http://www.slideshare.net/SoftwareStartUpAcademyOsijek/c-igor-rali

http://www.slideshare.net/DonchoMinkov/objectoriented-programmingwith-c

http://www.slideshare.net/TelerikAcademy/25-object-oriented-programming-principles-c-fundamentals