530 likes | 693 Views
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.
E N D
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 • 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.
The Anatomy of a Class Classes are usually written by this pattern: classClassName { declaration of attributes constructors properties methods }
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; }
Methods public bool Withdraw(double amount) public void Deposite(double amout) public void GiveInterest()
Properties public intInterestRate { get{return interestRate;} set{if( value>=0) interestRate = value;} }
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 . Means aggregation
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) Goes for aggregation as well.
Implementing 1 - 1 public class Customer{ //… private BankAccount account; //… account= new BankAccount(no, ir, bal); The association is implemented by an object reference (attribute). Customer is responsible for creating BankAccount objects.
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)
In the Code public class Customer{ //… private List<BankAccount>accounts; //… public Customer(intcNo, string n){ //… accounts = new List<BankAccount>(); } public void AddAccount(BankAccount acc){ accounts.Add(acc); } //… View Source
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.
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:
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
Class diagram View Source (dome-v1)
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
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
Inheritance in C# no change here public class Item { ... } change here public class DVD : Item { ... } public class CD : Item { ... } View Source (dome-v2)
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); Subtyping Static type Dynamic type
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.}
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.)
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.
Object diagram Static type Dynamic type
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! What we want What we have title: A Swingin' Affair (64 mins)* my favourite Sinatra album title: O Brother, Where Art Thou? (106 mins) The Coen brothers’ best movie!
The inheritance hierarchy Here we only know information in Item
Overriding: the solution print method in both super- and subclasses. Satisfies both static and dynamic type checking. View Source (dome-v3)
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?
Method lookup No inheritance or polymorphism. The obvious method is selected.
Method lookup Inheritance but no overriding. The inheritance hierarchy is ascended, searching for a match.
Method lookup Polymorphism and overriding. The ‘first’ version found (starting at the bottom of the hierarchy) is used.
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.
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.
Defining and Calling an overridden method public class Item { ... public virtual void Print() { --- } ... } public class CD : Item { ... public override void Print() { base.Print(); --- } ... }
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.
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.
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.
Example: • On Employee there is a method GiveBonus() which may have different implementations in the superclass and in the subclasses.
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.
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();
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).
Polymorphism/Dynamic Binding Static type The way it used to be: Employee programmer = new Employee(“H. Acker","Programmer",22222); Static type = Dynamic type Static method call Dynamic type Statictype • 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
Example • Let’s look at the implementation of the model from earlier source Now: Employees at the cantina get double bonus.
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.)
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
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: interfaceIEmployee { voidGiveBonus(doubleamount); stringName { get; set; } doubleSalery { get; set; } stringToString(); }
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).