session 2: oop in c# oop in c#: –object interaction. –inheritance and polymorphism. autumn...
TRANSCRIPT
Session 2: OOP in C#
• OOP in C#:– Object Interaction. – Inheritance and Polymorphism.
Autumn 2012 1UCN Technology: IT/Computer Science
Autumn 2012 UCN Technology: IT/Computer Science 2
Object-Oriented Programming
“ The Three Pillars of OOP”:Encapsulation
InheritancePolymorphism
The Substitution Principle
Autumn 2012 UCN Technology: IT/Computer Science 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.
Autumn 2012 UCN Technology: IT/Computer Science 4
The Anatomy of a Class
Classes are usually written by this pattern:
class ClassName
{
declaration of attributes
constructors
properties
methods
}
Autumn 2012 UCN Technology: IT/Computer Science 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;
}
Autumn 2012 UCN Technology: IT/Computer Science 6
Methods
public bool Withdraw(double amount)
public void Deposite(double amout)
public void GiveInterest()
Autumn 2012 UCN Technology: IT/Computer Science 7
Properties
public int InterestRate
{
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 .
Autumn 2012 UCN Technology: IT/Computer Science 8
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)
Autumn 2012 UCN Technology: IT/Computer Science 9Goes for aggregation as well.
public class Customer{//…private BankAccount account;//…
account= new BankAccount(no, ir, bal);
Autumn 2012 UCN Technology: IT/Computer Science 10
Customer is responsible for creating BankAccount objects.
The association is implemented by an
object reference (attribute).
Implementing 1 - 1
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)
Autumn 2012 UCN Technology: IT/Computer Science 11
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);}
//…
Autumn 2012 UCN Technology: IT/Computer Science 12
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.
Autumn 2012 UCN Technology: IT/Computer Science 13
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:
Autumn 2012 UCN Technology: IT/Computer Science 14
Autumn 2012 UCN Technology: IT/Computer Science 15
Exercise:Re-cap and getting started
• Create a VS project using this code:EmpProjectV1.rar
• Test it – understand it.
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
Autumn 2012 16UCN Technology: IT/Computer Science
DoME objects
Autumn 2012 17UCN Technology: IT/Computer Science
DoME object model
Autumn 2012 18UCN Technology: IT/Computer Science
Class diagram
View Source (dome-v1)
Autumn 2012 19UCN Technology: IT/Computer Science
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
Autumn 2012 20UCN Technology: IT/Computer Science
Using inheritance
Autumn 2012 21UCN Technology: IT/Computer Science
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
Autumn 2012 22UCN Technology: IT/Computer Science
Inheritance in C#
public class Item{ ...}
public class CD : Item{ ...}
public class DVD : Item { ...}
no change here
change here
View Source (dome-v2)
Autumn 2012 23UCN Technology: IT/Computer Science
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
Autumn 2012 24UCN Technology: IT/Computer Science
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.}
Autumn 2012 25UCN Technology: IT/Computer Science
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 .)
Autumn 2012 26UCN Technology: IT/Computer Science
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.
Autumn 2012 27UCN Technology: IT/Computer Science
Object diagram
Static type
Dynamic type
Autumn 2012 28UCN Technology: IT/Computer Science
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
Autumn 2012 29UCN Technology: IT/Computer Science
The inheritance hierarchy
Here we only know information in Item
Autumn 2012 30UCN Technology: IT/Computer Science
Overriding: the solution
print method in both super-
and subclasses.
Satisfies both static and
dynamic type checking.
View Source (dome-v3)
Autumn 2012 31UCN Technology: IT/Computer Science
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?
Autumn 2012 32UCN Technology: IT/Computer Science
Method lookup
No inheritance or polymorphism.
The obvious method is selected.Autumn 2012 33UCN Technology: IT/Computer Science
Method lookup
Inheritance but no overriding. The
inheritance hierarchy is ascended, searching for
a match.Autumn 2012 34UCN Technology: IT/Computer Science
Method lookup
Polymorphism and overriding. The ‘first’
version found (starting at the
bottom of the hierarchy) is used.Autumn 2012 35UCN Technology: IT/Computer Science
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.
Autumn 2012 36UCN Technology: IT/Computer Science
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.Autumn 2012 37UCN Technology: IT/Computer Science
Defining and Calling an overridden method
public class CD : Item{ ... public override void Print() { base.Print(); --- } ...}
public class Item{ ... public virtual void Print() {
--- } ...}
Autumn 2012 38UCN Technology: IT/Computer Science
Autumn 2012 UCN Technology: IT/Computer Science 39
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.
Autumn 2012 UCN Technology: IT/Computer Science 40
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.
Autumn 2012 UCN Technology: IT/Computer Science 41
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.
Autumn 2012 UCN Technology: IT/Computer Science 42
Example:
• On Employee there is a method GiveBonus() which may have different implementations in the superclass and in the subclasses.
Manager
noOfOpts
SalesPerson
sale
Employee
namesaleryposition
WorksOn
hours0..*1 0..*1
Project
namedepartment
10..* 10..*
Autumn 2012 UCN Technology: IT/Computer Science 43
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.
Autumn 2012 UCN Technology: IT/Computer Science 44
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();
Autumn 2012 UCN Technology: IT/Computer Science 45
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).
Autumn 2012 UCN Technology: IT/Computer Science 46
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
Autumn 2012 UCN Technology: IT/Computer Science47
Example
• Let’s look at the implementation of the model from earlier
Manager
noOfOpts
SalesPerson
sale
Employee
namesaleryposition
WorksOn
hours0..*1 0..*1
Project
namedepartment
10..* 10..*
source
Now: Employees at the cantina get double bonus.
Autumn 2012 UCN Technology: IT/Computer Science 48
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.)
Autumn 2012 UCN Technology: IT/Computer Science 49
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:
interface IEmployee { void GiveBonus(double amount); string Name { get; set; } double Salery { get; set; } string ToString(); }
Autumn 2012 50UCN Technology: IT/Computer Science
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).
Autumn 2012 51UCN Technology: IT/Computer Science
Autumn 2012 UCN Technology: IT/Computer Science 52
Example/Exercise: German Student
ExerciseGermanStudents.pdf
Autumn 2012 UCN Technology: IT/Computer Science 53
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... }