introduction to oop

68
INTRODUCTION TO OOP Session 4

Upload: flavius-demian

Post on 17-Jul-2015

108 views

Category:

Software


1 download

TRANSCRIPT

INTRODUCTION TO OOP

Session 4

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

Agenda

What is OOP

OOP and .NET

Classes, objects, constructors

Encapsulation

Access Modifiers

The static keyword

Static vs Non-Static

Class inheritance

Agenda

Polymorphism

Method overloading

Method overriding

Abstract class

Sealed class

Interfaces

Interfaces vs abstract classes

Boxing and unboxing

The const keyword

Agenda

The readonly keyword

Properties

Indexers

The is and as keywords

Lists

Dictionaries

Queues

Stacks

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.

What is 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.

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();

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}

}

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.

Encapsulation

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)

Access Modifiers

Demo

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.

The static keyword

static class SampleClass

{

static string myString = “My static string”;

}

private static void Main(string[] args)

{

Console.Write(SampleClass.myString);

}

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

The static keyword

Demo

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.

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

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)

Class inheritance

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

Class inheritance

Demo 3,4

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.

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

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.

Overloading

Demo

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 };

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.

Overriding

Overriding

Demo

Polymorphism

Polymorphism

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.

Abstract class

public abstract class MyAbstractClass

{

public abstract void DoWork();

}

public class RealClass : MyAbstractClass

{

public override void DoWork()

{

// code here

}

}

Abstract class

Demo

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.

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

}

}

Sealed class

public sealed class MySealedClass

{

//methods here

}

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

public sealed class RealClass : MySealedClass

{

}

Sealed class

Demo

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.

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.

Interface

To define an interface:

Interface ISampleInterface

{

void doSomething();

}

To implement and interface in a class:

class SampleClass : ISampleInterface

{

void doSomething()

{ // code here }

}

Interface

Demo

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.

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

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;

}

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;

}

}

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 .

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.

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; }

}

}

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;

}}

}

Properties

Demo

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; }

}}

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]);

Indexers

Demo

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;

}

The is and as keywords

Demo

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 );

}

List

Demo

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);

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 ());

}

Dictionary

Demo

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,

Queue

Demo

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

Stack

Demo

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