Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 OOP in C#:Object Interaction. Inheritance and Polymorphism. Session 2: OOP in C#

Similar presentations

Presentation on theme: "1 OOP in C#:Object Interaction. Inheritance and Polymorphism. Session 2: OOP in C#"— Presentation transcript:

1 1 OOP in C#:Object Interaction. Inheritance and Polymorphism. Session 2: OOP in C#

2 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle 2

3 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.

4 4 The Anatomy of a Class Classes are usually written by this pattern: class ClassName { declaration of attributes constructors properties methods }

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

6 6 Methods public bool Withdraw(double amount) public void Deposite(double amout) public void GiveInterest()

7 7 Properties public int InterestRate { get{return interestRate;} set{if( value>=0) interestRate = value;} }

8 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

9 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) 9 Goes for aggregation as well.

10 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

11 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

12 In the Code public class Customer{ //… private List accounts; //… public Customer(int cNo, string n){ //… accounts = new List (); } public void AddAccount(BankAccount acc){ accounts.Add(acc); } //… 12 View Source

13 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

14 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

15 The DoME example (from Kölling and Barnes: “Objects First…”) "Database of Multimedia Entertainment" stores details about CDs and DVDs CD: title, artist, # tracks, playing time, got-it, comment DVD: title, director, playing time, got-it, comment allows (later) to search for information or print lists 15

16 DoME objects 16

17 DoME object model 17

18 Class diagram View Source (dome-v1)dome-v1 18

19 Critique of DoME code duplication CD and DVD classes very similar (large part are identical) makes maintenance difficult/more work introduces danger of bugs through incorrect maintenance code duplication also in Database class 19

20 Using inheritance 20

21 Using inheritance define one base or super class: Item define subclasses for DVD and CD the super class defines common attributes the subclasses inherit the super class attributes the subclasses add own attributes 21

22 Inheritance in C# public class Item {... } public class CD : Item {... } public class DVD : Item {... } no change here change here View Source (dome-v2)dome-v2 22

23 Subtyping First, we had: public void AddCD( CD theCD) public void Add DVD ( DVD the DVD ) Now, we have: public void AddItem( Item theItem) We call this method with: DVD dvd = new DVD (...) ; myDB.AddItem(my DVD ); Static type Dynamic type 23

24 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

25 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

26 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

27 Object diagram Static type Dynamic type 27

28 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

29 The inheritance hierarchy Here we only know information in Item 29

30 Overriding: the solution print method in both super- and subclasses. Satisfies both static and dynamic type checking. View Source (dome-v3)dome-v3 30

31 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

32 Method lookup No inheritance or polymorphism. The obvious method is selected. 32

33 Method lookup Inheritance but no overriding. The inheritance hierarchy is ascended, searching for a match. 33

34 Method lookup Polymorphism and overriding. The ‘first’ version found (starting at the bottom of the hierarchy) is used. 34

35 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

36 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

37 Defining and Calling an overridden method public class CD : Item {... public override void Print() { base.Print(); --- }... } public class Item {... public virtual void Print() { --- }... } 37

38 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.

39 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.

40 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.

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

42 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.

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

44 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).

45 45 Polymorphism/Dynamic Binding The 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

46 46 Example Let’s look at the implementation of the model from earlier source Now: Employees at the cantina get double bonus.

47 47 Inheritance - design considerations If 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.)

48 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

49 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

50 Why use interfaces? Formalise system design before implementation especially 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 inheritance A class may implement several interfaces, but only inherit one class. (No competing implementations). 50

51 51 Example/Exercise: German Student ExerciseGermanStudents.pdf

52 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 ==; // equal, if ids are... }

Download ppt "1 OOP in C#:Object Interaction. Inheritance and Polymorphism. Session 2: OOP in C#"

Similar presentations

Ads by Google