Advanced Concepts Svetlin Nakov Telerik Corporation .

50
Object Oriented Programming Advanced Concepts Svetlin Nakov Telerik Corporation www.telerik. com

Transcript of Advanced Concepts Svetlin Nakov Telerik Corporation .

Page 1: Advanced Concepts Svetlin Nakov Telerik Corporation .

Object Oriented Programming

Advanced Concepts

Svetlin NakovTelerik

Corporationwww.telerik.com

Page 2: Advanced Concepts Svetlin Nakov Telerik Corporation .

Table of Contents

1. Inheritance What is Inheritance? Inheritance Hierarchy Transitive Inheritance

2. Encapsulation and Data Abstraction

3. Cohesion and Coupling

4. Polymorphism Abstract Classes Virtual Methods

2

Page 3: Advanced Concepts Svetlin Nakov Telerik Corporation .

InheritanceHow and When to Use It?

Page 4: Advanced Concepts Svetlin Nakov Telerik Corporation .

What is Inheritance? The ability of a class to implicitly gain all members of another class

The class that gains new functionality is called derived class

The class whose methods are inherited is called base class to his derived class

Inheritance establishes an is-a relationship between classes: A is B

4

Page 5: Advanced Concepts Svetlin Nakov Telerik Corporation .

How to Define Inheritance?

We must specify the name of the base class after the name of the derived

In the constructor of the derived class we use the keyword base to invoke the constructor of the base class

5

public class Shape{...}public class Circle : Shape{...}

public Circle (int x, int y) : base(x){...}

Page 6: Advanced Concepts Svetlin Nakov Telerik Corporation .

Simple Inheritance Example

public class Mammal{ private int age;

public Mammal(int age) { this.age = age; }

public int Age { get { return age; } set { age = value; } }

public void Sleep() { Console.WriteLine("Shhh! I'm sleeping!"); }}

6

Page 7: Advanced Concepts Svetlin Nakov Telerik Corporation .

Simple Inheritance Example (2)

public class Dog : Mammal{ private string breed; public Dog(int age, string breed) : base(age) { this.breed = breed; }

public string Breed { get { return breed; } set { breed = value; } } public void WagTail() { Console.WriteLine("Tail wagging..."); }}

7

Page 8: Advanced Concepts Svetlin Nakov Telerik Corporation .

Simple Inheritance

Live Demo

Page 9: Advanced Concepts Svetlin Nakov Telerik Corporation .

Inheritance Hierarchy Using inheritance we create inheritance hierarchy Easily represented by UML class

diagrams

Classes are represented by rectangles containing the methods and data that belong to them

Relations between classes are represented by arrows

9

Page 10: Advanced Concepts Svetlin Nakov Telerik Corporation .

Class Diagram – Example

10

Shape

#mPosition:Point

structPoint

+mX:int+mY:int

+Point

interfaceISurfaceCalculatable

+CalculateSurface:int

Rectangle

-mWidth:int-mHeight:int

+Rectangle+CalculateSurface:int

Square

-mSize:int

+Square+CalculateSurface:int

FilledSquare

-mColor:Color

+FilledSquare

structColor

+mRedValue:byte+mGreenValue:byte+mBlueValue:byte

+Color

FilledRectangle

-mColor:Color

+FilledRectangle

10

Page 11: Advanced Concepts Svetlin Nakov Telerik Corporation .

Accessibility Levels Access modifiers in C#

public – access is not restricted private – access is restricted to the containing type

protected – access is limited to the containing type and types derived from it

internal – access is limited to the current assembly

protected internal – access is limited to the current assembly or types derived from the containing class

11

Page 12: Advanced Concepts Svetlin Nakov Telerik Corporation .

Important Aspects

Structures cannot be inherited

In C# there is no multiple inheritance

Instance constructors, destructors, and static constructors are not inherited

Inheritance is transitive.

If C is derived from B, and B is derived from A, then C inherits A as well 12

Page 13: Advanced Concepts Svetlin Nakov Telerik Corporation .

Transitive Inheritance

class Creature{ public void Walk() { Console.WriteLine("Walking ...."); }}

class Mammal : Creature{ //The same as Simple Inheritance Example…}

class Dog : Mammal{ //The same as Simple Inheritance Example…}

13

Page 14: Advanced Concepts Svetlin Nakov Telerik Corporation .

Transitive Inheritance (2)

class MainClass{ static void Main() { Dog Joe = new Dog(6, "labrador"); Joe.Walk(); }}

14

class MainClass{ static void Main() { Dog Joe = new Dog(6, "labrador"); Joe.Walk(); }}

Page 15: Advanced Concepts Svetlin Nakov Telerik Corporation .

Transitive Inheritance

Live Demo

Page 16: Advanced Concepts Svetlin Nakov Telerik Corporation .

Important Features A derived class extends its base class It can add new members but cannot

remove derived ones A derived class can hide inherited members by declaring new members with the same name or signature

A class can declare virtual methods and properties Derived classes can override the

implementation of these members

16

Page 17: Advanced Concepts Svetlin Nakov Telerik Corporation .

Encapsulation and Data

Abstraction

Page 18: Advanced Concepts Svetlin Nakov Telerik Corporation .

Encapsulation Encapsulation is one of the basic principles when using objects and inheritance

Encapsulation is the ability to hide the internal data and methods of an object So that only the essential for using

it parts to be programmatically accessible

The exact implementation of methods and data members remains hidden

Only vital information about the object is presented

18

Page 19: Advanced Concepts Svetlin Nakov Telerik Corporation .

Data Abstraction

The ability to work with data without concern about its exact implementation, knowing only the operations we can perform on it

Data abstraction simplifies the programming process

Data abstraction usually imitates well known processes from the real world

19

Page 20: Advanced Concepts Svetlin Nakov Telerik Corporation .

Cohesion and Coupling

Page 21: Advanced Concepts Svetlin Nakov Telerik Corporation .

Cohesion Cohesion describes how closely all the routines in a class or all the code in a routine support a central purpose

Cohesion must be strong Classes must contain strongly related functionality and aim for single purpose

Cohesion is a useful tool for managing complexity

Well-defined abstractions keep cohesion strong 21

Page 22: Advanced Concepts Svetlin Nakov Telerik Corporation .

Good and Bad Cohesion

Good: hard disk, cdrom, floppy

BAD: spaghetti code

22

Page 23: Advanced Concepts Svetlin Nakov Telerik Corporation .

Strong Cohesion Strong cohesion example

Class Math that has methods:Sin(), Cos(), Asin()Sqrt(), Pow(), Exp()Math.PI, Math.E

23

double sideA = 40, sideB = 69;double angleAB = Math.PI / 3;

double sideC = Math.Pow(sideA, 2) + Math.Pow(sideB, 2) - 2 * sideA * sideB * Math.Cos(angleAB);

double sidesSqrtSum = Math.Sqrt(sideA) + Math.Sqrt(sideB) + Math.Sqrt(sideC);

Page 24: Advanced Concepts Svetlin Nakov Telerik Corporation .

Bad Cohesion Bad cohesion example

Class Magic that has these methods:

Another example:

24

public void PrintDocument(Document d);public void SendEmail(string recipient, string subject, string text);public void CalculateDistanceBetweenPoints(int x1, int y1, int x2, int y2)

MagicClass.MakePizza("Fat Pepperoni");MagicClass.WithdrawMoney("999e6");MagicClass.OpenDBConnection();

Page 25: Advanced Concepts Svetlin Nakov Telerik Corporation .

Coupling Coupling describes how tightly a class or routine is related to other classes or routines

Coupling must be kept loose Modules must depend little on each

other

All classes and routines must have small, direct, visible, and flexible relations to other classes and routines

One module must be easily used by other modules

25

Page 26: Advanced Concepts Svetlin Nakov Telerik Corporation .

Loose and Tight Coupling

Loose Coupling:

Easily replace old

HDD

Easily place this HDD

to another

motherboard

Tight Coupling:

Where is the video

adapter?

Can you change the

video controller?

26

Page 27: Advanced Concepts Svetlin Nakov Telerik Corporation .

Loose Coupling - Example

class Report{ public bool LoadFromFile(string fileName) {…} public bool SaveToFile(string fileName) {…}}

class Printer{ public static int Print(Report report) {…}}

class Program{ static void Main() { Report myReport = new Report(); myReport.LoadFromFile("C:\\DailyReport.rep"); Printer.Print(myReport); }}

27

Page 28: Advanced Concepts Svetlin Nakov Telerik Corporation .

Tight Coupling - Example

class MathParams{ public static double operand; public static double result;}

class MathUtil{ public static void Sqrt() { MathParams.result = CalcSqrt(MathParams.operand); }} // … static void Main() { MathParams.operand = 64; MathUtil.Sqrt(); Console.WriteLine(MathParams.result); }}

28

Page 29: Advanced Concepts Svetlin Nakov Telerik Corporation .

Spaghetti Code Combination of bad cohesion and

tight coupling:

29

class Report{ public void Print() {…} public void InitPrinter() {…} public void LoadPrinterDriver(string fileName) {…} public bool SaveReport(string fileName) {…} public void SetPrinter(string printer) {…}

}

class Printer{ public void SetFileName() {…} public static bool LoadReport() {…} public static bool CheckReport() {…}}

Page 30: Advanced Concepts Svetlin Nakov Telerik Corporation .

Polymorphism

Page 31: Advanced Concepts Svetlin Nakov Telerik Corporation .

Polymorphism Polymorphism is the ability for classes to provide different implementations of methods called by the same name

It allows a method of a class to react differently depending on the object it is used on

Polymorphism allows change in implementation of virtual methods

Polymorphism in components is usually implemented through abstract classes and virtual methods 31

Page 32: Advanced Concepts Svetlin Nakov Telerik Corporation .

Abstract Class An abstract class is a class that cannot be instantiated itself – it must be inherited

Some or all members of the class can be unimplemented, the inheriting class must provide implementation

Members that are implemented might still be overridden using the keyword override

32

Page 33: Advanced Concepts Svetlin Nakov Telerik Corporation .

Virtual Methods Virtual method is method that can be used in the same way on instances of base and derived classes but its implementation is different

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

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

33

public virtual void CalculateSurface()

Page 34: Advanced Concepts Svetlin Nakov Telerik Corporation .

The override Modifier Using override we can modify a method or property

An override method provides a new implementation of a member inherited from a base class

You cannot override a non-virtual or static method

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

34

Page 35: Advanced Concepts Svetlin Nakov Telerik Corporation .

Polymorphism – Example

35

class Creature{ public virtual void Speak() {}}

class Cat : Creature{ public override void Speak() { Console.WriteLine("Miaaay!"); }}

class Dog : Creature{ public override void Speak() { Console.WriteLine("Bark, bark, Grrrr!"); }}

Page 36: Advanced Concepts Svetlin Nakov Telerik Corporation .

Polymorphism – Example (2)

36

static void Main(){ Creature[] creatures = new Creature[] { new Dog(), new Cat() }; foreach (Creature animal in creatures) { string name = animal.GetType().Name; Console.WriteLine("{0}: ", name);

animal.Speak(); }}

Page 37: Advanced Concepts Svetlin Nakov Telerik Corporation .

PolymorphismLive Demo

Page 38: Advanced Concepts Svetlin Nakov Telerik Corporation .

Abstract Classes – Example

38

public abstract class Animal{ abstract public int Speed { get; }}public class Cheetah : Animal{ public override int Speed { get { return 100; } }}public class Turtle : Animal{ public override int Speed { get { return 1; } }}

Page 39: Advanced Concepts Svetlin Nakov Telerik Corporation .

Abstract Classes – Example (2)

39

static void Main(){ Turtle snail = new Turtle(); int speed = snail.Speed;

Console.Write("Thr turtle can go{0}km/h", speed); Console.WriteLine(); Cheetah cheetah = new Cheetah(); speed = cheetah.Speed; Console.Write("The cheetah can go {0}km/h", speed); Console.WriteLine();}

Page 40: Advanced Concepts Svetlin Nakov Telerik Corporation .

Abstract ClassesLive Demo

Page 41: Advanced Concepts Svetlin Nakov Telerik Corporation .

When to Use Polymorphism?

When you need a group of components with identical functionality

When you need base classes to remain easily modifiable and flexible

Polymorphism require more designing best used in small-scale

development tasks 41

Page 42: Advanced Concepts Svetlin Nakov Telerik Corporation .

Summary Inheritance – one of the basic characteristics of OOP

Inheritance hierarchy visualization and design

Basic inheritance practices – abstraction and encapsulation

Basic inheritance characteristics – cohesion and coupling

Polymorphism – when and why to use it

42

Page 43: Advanced Concepts Svetlin Nakov Telerik Corporation .

Object Oriented Programming

Questions? ?

?? ? ?

???

?

?

Page 44: Advanced Concepts Svetlin Nakov Telerik Corporation .

Exercises

1. Define class Human with first name and last name. Define new class Student which is derived from Human and has new field – grade. Define class Worker derived from Human with new field weekSalary and work-hours per day and method MoneyPerHour() that returns money earned by hour by the worker. Define the proper constructors and properties for this hierarchy.

44

Page 45: Advanced Concepts Svetlin Nakov Telerik Corporation .

Exercises (2)

Initialize an array of 10 students and sort them by grade in ascending order. Initialize an array of 10 workers and sort them by Money per hour in descending order.

2. Define class shape with only one virtual method CalculateSurface() and fields width and height. Define two new classes Triangle and Rectangle that implement the virtual method. This method must return the surface of the figure

45

Page 46: Advanced Concepts Svetlin Nakov Telerik Corporation .

Exercises (3) (height*width for rectangle and

height*width/2 for triangle). Define class Circle and suitable constructor so that on initialization height must be kept equal to width and implement the CalculateSurface() method.

3. Write a program that tests the behavior of the CalculateSurface() method for different shape (Circle, Rectangle, Triangle) objects, stored in an array.

46

Page 47: Advanced Concepts Svetlin Nakov Telerik Corporation .

Exercises (5)

4. Create a hierarchy Dog, Frog, Cat, Kitten, Tomcat and define suitable constructors and methods according to the following rules:

All of this are Animals. Kittens and tomcats are cats. All animals are described by age, name and sex. Kittens can be only female and tomcats can be only male. Each animal produce a sound. Create arrays of different kinds of animals and calculate the average age of each kind of animal using static methods. Create static method in the animal class that identifies the animal by its sound.

47

Page 48: Advanced Concepts Svetlin Nakov Telerik Corporation .

Exercises (6)

5. A bank holds different types of accounts for its customers: deposit accounts, loan accounts and mortgage accounts. Customers could be individuals or companies.

All accounts have customer, balance and interest rate (monthly based). Deposit accounts are allowed to deposit and with draw money. Loan and mortgage accounts can only deposit money.

48

Page 49: Advanced Concepts Svetlin Nakov Telerik Corporation .

Exercises (7)All accounts can calculate their interest amount for a given period (in months). In the common case its is calculated as follows: number_of_months * interest_rate.Loan accounts have no interest for the first 3 months if are held by individuals and for the first 2 months if are held by a company.Deposit accounts have no interest if their balance is positive and less than 1000.Mortgage accounts have ½ interest for the first 12 months for companies and no interest for the first 6 months for individuals.

49

Page 50: Advanced Concepts Svetlin Nakov Telerik Corporation .

Exercises (8)

Your task is to write a program to model the bank system by classes and interfaces. You should identify the classes, interfaces, base classes and abstract actions and implement the calculation of the interest functionality.

50