+ All Categories
Home > Documents > Session 2: OOP in C#

Session 2: OOP in C#

Date post: 23-Feb-2016
Category:
Upload: radwan
View: 38 times
Download: 0 times
Share this document with a friend
Description:
Session 2: OOP in C# . OOP in C#: Object Interaction. Inheritance and Polymorphism. Object-Oriented Programming. “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle. OO-Principles -encapsulation. - PowerPoint PPT Presentation
52
1 OOP in C#:Object Interaction. Inheritance and Polymorphism. Session 2: OOP in C#
Transcript
Page 1: Session 2: OOP in C#

1

OOP in C#:Object Interaction. Inheritance and Polymorphism.

Session 2: OOP in C#

Page 2: Session 2: OOP in C#

Object-Oriented Programming

“ The Three Pillars of OOP”:EncapsulationInheritancePolymorphism

The Substitution Principle

2

Page 3: Session 2: OOP in C#

3

OO-Principles-encapsulation

Seen from the outside an object is an entity offering a number of services (public methods and properties).The implementation and data representation are hidden or encapsulated.

This makes it possible to change implementation without affecting other parts of the program.Also it becomes possible to think, talk and use the object without knowing the implementation.Hiding data behind methods and properties are called encapsulation or data abstraction.

Encapsulation or data abstraction is one the fundamental principles of object-oriented programming.

Page 4: Session 2: OOP in C#

4

The Anatomy of a Class

Classes are usually written by this pattern:

class ClassName {

declaration of attributesconstructorspropertiesmethods

}

Page 5: Session 2: OOP in C#

5

The Class BankAccount- attributes and constructor

namespace Banking{

public class BankAccount{

private double balance;private int accNo;private int interestRate;

public BankAccount(int no, int ir){

balance = 0;accNo = no;intrestRate = ir;

}

Page 6: Session 2: OOP in C#

6

Methods

public bool Withdraw(double amount)

public void Deposite(double amout)

public void GiveInterest()

Page 7: Session 2: OOP in C#

7

Properties

public int InterestRate{

get{return interestRate;}set{if( value>=0) interestRate = value;}

}

Page 8: Session 2: OOP in C#

Object Interaction

Objects may be connected in different ways:Association (“know-of-relation”).One object uses another.

Aggregation (“part-of-relation”).One object is a part of another.

The distinction is not always clear .

8

Means aggregation

Page 9: Session 2: OOP in C#

Cardinality or Multiplicity

Tells how many objects an object may be associated with:

One customer may have one account, an account must belong to a customer. (1 – 1)

One customer may have many accounts, an account must belong to one customer. (1 – n)

A customer may one or more accounts, an account may belong to one or more customers. (n – m)

9Goes for

aggregation as well.

Page 10: Session 2: OOP in C#

public class Customer{//…private BankAccount account;//…

account= new BankAccount(no, ir, bal);

10

Customer is responsible for creating BankAccount objects.

The association is implemented by an

object reference (attribute).

Implementing 1 - 1

Page 11: Session 2: OOP in C#

Implementing 1 - n

One customer may have many accounts, an account must belong to one customer.

Possible solution: A collection of BankAccounts in Customer (accounts)

11

Page 12: Session 2: OOP in C#

In the Code

public class Customer{ //…

private List<BankAccount> accounts; //… public Customer(int cNo, string n){

//… accounts = new List<BankAccount>();

}public void AddAccount(BankAccount acc){accounts.Add(acc);}

//…

12

View Source

Page 13: Session 2: OOP in C#

Implementing n - m

A customer may have one or more accounts, an account may belong to one or more customers.

Possible solution: A collection of BankAccounts in Customer (accounts) and a collection of Customers (owners) in BankAccount.

13

Page 14: Session 2: OOP in C#

Example: Project Management

An employee may work on several projects.A project may have several employees working on it.We need to record the number of hours a given employee has spent on a given project:

14

Page 15: Session 2: OOP in C#

The DoME example(from Kölling and Barnes: “Objects First…”)

"Database of Multimedia Entertainment"

stores details about CDs and DVDsCD: title, artist, # tracks, playing time, got-it, commentDVD: title, director, playing time, got-it, comment

allows (later) to search for information or print lists

15

Page 16: Session 2: OOP in C#

DoME objects

16

Page 17: Session 2: OOP in C#

DoME object model

17

Page 18: Session 2: OOP in C#

Class diagram

View Source (dome-v1)

18

Page 19: Session 2: OOP in C#

Critique of DoME

code duplicationCD and DVD classes very similar (large part are identical)makes maintenance difficult/more workintroduces danger of bugs through incorrect maintenance

code duplication also in Database class

19

Page 20: Session 2: OOP in C#

Using inheritance

20

Page 21: Session 2: OOP in C#

Using inheritance

define one base or super class: Itemdefine subclasses for DVD and CDthe super class defines common attributesthe subclasses inherit the super class attributesthe subclasses add own attributes

21

Page 22: Session 2: OOP in C#

Inheritance in C#

public class Item{ ...}

public class CD : Item{ ...}

public class DVD : Item { ...}

no change here

change here

View Source (dome-v2)

22

Page 23: Session 2: OOP in C#

Subtyping

First, we had:public void AddCD(CD theCD)public void AddDVD(DVD theDVD)

Now, we have:public void AddItem(Item theItem)

We call this method with:DVD dvd = new DVD(...);

myDB.AddItem(myDVD);

Static type

Dynamic type

23

Page 24: Session 2: OOP in C#

Static and dynamic type

The declared type of a variable is its static type.The type of the object a variable refers to is its dynamic type.The compiler’s job is to check for static-type violations.

for(Item item : items) { item.Print(); // Item must have

// declared a Print method.}

24

Page 25: Session 2: OOP in C#

Subclasses and subtyping

Classes define types.Subclasses define subtypes.Objects of subclasses can be used where objects of supertypes are required.(This is called substitution .)

25

Page 26: Session 2: OOP in C#

Polymorphic variables

Object variables in C# are polymorphic.

(They can reference objects of more than one type.)

They can reference objects of the declared type, or of subtypes of the declared type.

26

Page 27: Session 2: OOP in C#

Object diagram

Static type

Dynamic type

27

Page 28: Session 2: OOP in C#

Conflicting output

CD: A Swingin' Affair (64 mins)* Frank Sinatra tracks: 16 my favourite Sinatra album DVD: O Brother, Where Art Thou? (106 mins) Joel & Ethan Coen The Coen brothers’ best movie!

title: A Swingin' Affair (64 mins)* my favourite Sinatra album

title: O Brother, Where Art Thou? (106 mins) The Coen brothers’ best movie!

What we want

What we have

28

Page 29: Session 2: OOP in C#

The inheritance hierarchy

Here we only know information in Item

29

Page 30: Session 2: OOP in C#

Overriding: the solution

print method in both super-

and subclasses.

Satisfies both static and

dynamic type checking.

View Source (dome-v3)

30

Page 31: Session 2: OOP in C#

Overriding

Superclass and subclass define methods with the same signature.Each has access to the fields of its class.Superclass satisfies static type check.Subclass method is called at runtime – it overrides the superclass version.What becomes of the superclass version?

31

Page 32: Session 2: OOP in C#

Method lookup

No inheritance or polymorphism.

The obvious method is selected.

32

Page 33: Session 2: OOP in C#

Method lookup

Inheritance but no overriding. The

inheritance hierarchy is ascended, searching for

a match.33

Page 34: Session 2: OOP in C#

Method lookup

Polymorphism and overriding. The ‘first’

version found (starting at the

bottom of the hierarchy) is used.

34

Page 35: Session 2: OOP in C#

Method lookup summary

The variable is accessed.The object stored in the variable is found.The class of the object is found.The class is searched for a method match.If no match is found, the superclass is searched.This is repeated until a match is found, or the class hierarchy is exhausted.Overriding methods take precedence.

35

Page 36: Session 2: OOP in C#

Call to base in methods

Overridden methods are hidden ...... but we often still want to be able to call them.An overridden method can be called from the method that overrides it.base.Method(...)Compare with the use of base in constructors.

36

Page 37: Session 2: OOP in C#

Defining and Calling an overridden method

public class CD : Item{ ... public override void Print() { base.Print(); --- } ...}

public class Item{ ... public virtual void Print() {

--- } ...}

37

Page 38: Session 2: OOP in C#

38

Inheritance in C#

Every method and property is inherited – constructors are not.private members are inherited, but not directly accessible in the subclass.Every protected member of the base class is visible in subclasses, but hidden from other parts of the program.Members may be added in the subclass. Multiple inheritance is not supported (by classes).In C# every class inherits from Object.

Page 39: Session 2: OOP in C#

39

OO-Principles -inheritance

Supports code-reuse.Existing classes may be extended through inheritance.Inheritance is to used as type specialisation, that is: we are modelling an “is-a” relationship between super- and subclass. For instance: CheckAccount is an Account, a special kind of account, but an account.So when we want to add specialised functionality to our system, inheritance may used by adding specialised classes.E.g.: CheckAccount may inherit Account.

Page 40: Session 2: OOP in C#

40

OO-Principles-inheritance

Terminology: baseclass/superclass – subclass.

Inheritance is to be used as specialisation/generalisation. Inheritance models an “is-a” relationship between super- and subclass.

A subclass is type compatible with the superclass:CheckAccount c = new CheckAccount();

if (c is Account) -- yields true, if CheckAccount inherits Account

The “is-a” relation is transitive.

Page 41: Session 2: OOP in C#

41

Example:

• On Employee there is a method GiveBonus() which may have different implementations in the superclass and in the subclasses.

ManagernoOfOpts

SalesPersonsale

Employeenamesaleryposition

WorksOnhours

0..*1 0..*1

Projectnamedepartment10..* 10..*

Page 42: Session 2: OOP in C#

42

Inheritance- Constructors

The base-part of a subclass is initialised by the call base(param-liste)

This call is executed as the first step in executing the constructor of the subclass:base(param-liste) is placed immediately after the method-heading of the constructor (C++ syntax) If you don’t provide a default constructor (a constructor with no parameters) a default constructor is generated by the compiler. This will be called implicitly when an object of the subclass is created.

Page 43: Session 2: OOP in C#

43

Inheritance - redefining methods

A method inherited from the base-class may be redefined (“overridden”) in the sub-class.For instance the Withdraw-method on Account/CheckAccout.In C# the must be specified “virtual” in the base-class and “override” in sub-class. The method in the sub-class has the same signature (name and parameter list) and the same return type as the method in the base-class.In the sub-class the redefined method in the base-class may be called using

base.methodName();

Page 44: Session 2: OOP in C#

44

Inheritance- polymorphism

All reference variables in C# may refer to objects of subtypes.In the case of virtual methods it is first at execution time it is determined which method exactly is to be called. The method called is the one defined on the object that the reference currently is referring to. This is called dynamic binding – the call is bound to an actual code segment at runtime (dynamically).

Page 45: Session 2: OOP in C#

45

Polymorphism/Dynamic BindingThe way it used to be:

Employee programmer = new Employee(“H. Acker","Programmer",22222);

Static type = Dynamic type

Static method call

Static type

Dynamic type

Using polymorphism::

Employee boss = new Manager(”Big Boss",”CEO",52525, 500);

Dynamic type must be the same or a sub-type of the static type.The compiler checks method-calls on the static type. Runtime the call is bonded to the dynamic type (dynamic binding).Dynamic binding requires methods to be specified virtual in the base-class and explicitly overridden in the sub-classes.

Dynamic type

Static type

Page 46: Session 2: OOP in C#

46

Example

Let’s look at the implementation of the model from earlier

ManagernoOfOpts

SalesPersonsale

Employeenamesaleryposition

WorksOnhours

0..*1 0..*1

Projectnamedepartment10..* 10..*

source

Now: Employees at the cantina get double bonus.

Page 47: Session 2: OOP in C#

47

Inheritance - design considerationsIf we need a class to hold a list of employees, and it should be possible to add employees at the end of list, but nowhere else. Should we inherit Array or ArrayList or…?

We are not to inherit at all!!! But use delegation.

Inheritance is not to be used senselessly trying to reuse code! Inheritance is to be seen as sub typing!

Inheritance models “is-a” relationships.

Code-reuse is obtainable by using existing classes (composition, delegation etc.)

Page 48: Session 2: OOP in C#

48

Inheritance - abstract classes

A class that defines one or more methods that are not implemented is called abstract. And the non-implemented methods are specified abstract.An abstract class can not be instantiated. It can only serve as base-class.An abstract class can only be used as static type, not dynamic type for object.Abstract methods must be implemented in the sub-classes. Otherwise the subclass itself becomes abstract.So an abstract method defines or specifies functionality (but does not implement) what must be implemented in the subclasses.Constructors in an abstract class are only used by the constructors in the subclasses

Page 49: Session 2: OOP in C#

Interfaces

An interface may be seen as a purely abstract class.Interface: only method signatures, no implementation! (All methods are abstract)

An interface represents a design.Example:

An interface to Employee:

interface IEmployee { void GiveBonus(double amount); string Name { get; set; } double Salery { get; set; } string ToString(); }

49

Page 50: Session 2: OOP in C#

Why use interfaces?

Formalise system design before implementationespecially useful with large systems.

Contract-based programming the interface represents the contract between client and object.

Low coupling!decouples specification and implementation.facilitates reusable client code.client code will work with both existing and future objects as long as the interface is not changed.

Multiple inheritanceA class may implement several interfaces, but only inherit one class. (No competing implementations).

50

Page 51: Session 2: OOP in C#

51

Example/Exercise: German Student

ExerciseGermanStudents.pdf

Page 52: Session 2: OOP in C#

52

C#- When are objects equal?

Classes ought to override the Equals-method inherited from Object

public class Customer{ . . .

public override bool Equals(object obj) { Customer other; if ((obj == null) || (!(obj is Customer))) return false; // surely not equal

other = (Customer) obj; // typecast to gain access return this.id == other.id; // equal, if ids are... }


Recommended