03 - inheritance and polymorphism. 2 © s. uchitel, 2004 modelling (1/2) a model should be an...

49
03 - Inheritance and 03 - Inheritance and Polymorphism Polymorphism

Upload: charla-stanley

Post on 18-Dec-2015

216 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

03 - Inheritance and 03 - Inheritance and PolymorphismPolymorphism

Page 2: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 2

Modelling (1/2)Modelling (1/2)

A model should be an A model should be an abstractabstract yet yet preciseprecise description of a system.description of a system. Abstract: Hides detailsAbstract: Hides details Precise: Unambiguous, with a clear meaningPrecise: Unambiguous, with a clear meaning

Models can be graphical or textual descriptionsModels can be graphical or textual descriptions The diagrams we have been using are part of the The diagrams we have been using are part of the

Unified Modelling Language (UML).Unified Modelling Language (UML). Class diagramsClass diagrams Object diagramsObject diagrams

area()perimeter()

cirlce1

colour= “red”diameter = 4

Page 3: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 3

Modelling (2/2)Modelling (2/2)

Model should support reasoning and Model should support reasoning and documentation.documentation.

Choose level of abstraction and scope Choose level of abstraction and scope appropriatelyappropriately

area()perimeter()

cirlce1

colour= “red”diameter = 4

<<instanceOf>> MyCar:CarCar

Car

colour:Stringmodel:StringfuelCapacity:int

start():voidstop():voidmove(direction:String):void

+ Dice()+ getTop(): int+ getBottom(): int

Dice

Page 4: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 4

Relation between ClassesRelation between Classes

Why think of relationships between classes?Why think of relationships between classes? Modelling perspective: Modelling perspective:

Manage complexity of the problem and solutionManage complexity of the problem and solution Analysis and Documentation.Analysis and Documentation.

Programming perspective: Programming perspective: Code reuse and readabilityCode reuse and readability Java provides constructs for supporting some kinds Java provides constructs for supporting some kinds

of relationshipsof relationships RelationshipsRelationships

DependencyDependency AssociationAssociation AggregationAggregation CompositionComposition Generalisation/SpecialisationGeneralisation/Specialisation

Strength

Page 5: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 5

DependencyDependency

Defines the “Defines the “usesuses” or “” or “knows aboutknows about” relationship.” relationship. If a class explicitly uses a type introduced by If a class explicitly uses a type introduced by

some class, then there is a some class, then there is a dependencydependency.. Indicates that a change in one class may affect Indicates that a change in one class may affect

the other.the other. Dependencies can be given names.Dependencies can be given names. Weakest relationship between classesWeakest relationship between classes

ChannelVideoClip

+play(on: channel);

plays-on

Page 6: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 6

AssociationAssociation

A specific kind of dependencyA specific kind of dependency Specifies a structural relation.Specifies a structural relation. Typically can be conceptually navigated in Typically can be conceptually navigated in

both directions.both directions. Programmatically, this may not be possibleProgrammatically, this may not be possible

May have rolesMay have roles May have cardinalitiesMay have cardinalities

PersonCompany * 1..*employmentemployer employee

Page 7: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 7

Aggregation and CompositionAggregation and Composition

Specific kind of associationSpecific kind of association Denote “Denote “part ofpart of” or “” or “hashas” relationship.” relationship. Composition is stronger that AggregationComposition is stronger that Aggregation

Parts are not sharedParts are not shared Parts existence depends on existence of the Parts existence depends on existence of the

wholewhole

Dice Random1

Composition

1Course Student

*

Aggregation

1

Page 8: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 8

Class Relationships: A Subtle issueClass Relationships: A Subtle issue

Sometimes it Sometimes it can be arguablecan be arguable as to as to whether the relation between classes is a whether the relation between classes is a dependency, association, composition, dependency, association, composition, aggregation.aggregation.

It is a It is a subtlesubtle issue issue For these 4 relations, the impact on the For these 4 relations, the impact on the

actual Java code is limited.actual Java code is limited. If you are not sure, you can use the If you are not sure, you can use the

weaker relationship. weaker relationship.

Page 9: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 9

Generalisation / SpecialisationGeneralisation / Specialisation

Denotes the “Denotes the “is-ais-a” or the “” or the “is-a-kind-ofis-a-kind-of”” It is the strongest kind of relation.It is the strongest kind of relation. InheritanceInheritance is the process of is the process of deriving deriving a a

specialised class from an existing class.specialised class from an existing class. Java supports inheritance explicitly trough Java supports inheritance explicitly trough

several language constructs.several language constructs.

Car

PetrolCar HydrogenCarElectricCar

Shape

Polygon

Rectangle

Page 10: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 10

Inheritance: Car ExampleInheritance: Car Example

An electric car “An electric car “is-ais-a” car that runs with an ” car that runs with an electric engine.electric engine.

Car is the Car is the superclass superclass or or parent-classparent-class of of ElectricCarElectricCar

Car is a Car is a generalisationgeneralisation of ElectricCar. of ElectricCar. ElectricCar is a ElectricCar is a subclasssubclass or a or a derived-classderived-class of Car of Car ElectricCar is a ElectricCar is a specialisationspecialisation of Car. of Car.

Car+ colour:String+ model:String+ mileage:int

+ start()+ stop()+ move()

ElectricCar- ElectricEngine

PetrolCar- PetrolEngine Petrol and Electric cars inherit

all public fields and methods from their superclass

Page 11: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 11

Inheritance: Student ExampleInheritance: Student Example

A PhD student “A PhD student “is-a-kind-ofis-a-kind-of” Student.” Student. Unlike other students it has a supervisor, must Unlike other students it has a supervisor, must

write a thesis and does not take courses. write a thesis and does not take courses. Like other students, it must register, is in a Like other students, it must register, is in a

department, receives a login, aims for a department, receives a login, aims for a degree.degree.

Student

PhdStudent

+getLogin()+setLogin()

+getSupervisor():String+getDetails():String

Undergraduate

+getPPT():String+getPMT():String+getTutor():String

Undergraduate and PhdStudentinherit all public fields and methods

from their superclass

Inherits getLogin()and setLogin()

Page 12: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 12

““Is a” vs “Is a kind of”Is a” vs “Is a kind of”

What is the difference?What is the difference? Are there new visible methods fields.Are there new visible methods fields. Does the visible behaviour change.Does the visible behaviour change.

An electric car is a carAn electric car is a car Has same visible methods and fieldsHas same visible methods and fields Has same visible behaviour (from the user;s perspective)Has same visible behaviour (from the user;s perspective)

A PhD student is a kind of studentA PhD student is a kind of student Has more methodsHas more methods Has different requirements for graduation.Has different requirements for graduation.

Practical implications? Practical implications? SubsitutabilitySubsitutability A method using PhdStudents may not work with StudentsA method using PhdStudents may not work with Students A method using ElectricCar should work with Cars.A method using ElectricCar should work with Cars. More on this later... More on this later...

Page 13: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 13

Inheritance: Lamp ExampleInheritance: Lamp Example

A lamp may be A lamp may be switched on or off by switched on or off by pressing a switch.pressing a switch.

An adjustable lamp An adjustable lamp inherits all properties inherits all properties of a lamp;in addition it of a lamp;in addition it can be dimmed.can be dimmed.

Lamp

#onOff:boolean

+Lamp(status:boolean)

+pressSwitch():void

+print():void

AdjLamp

-brightness:double

+AdjLamp(onOrOff:boolean)

+dim():void

+print():void

“protected” visibility

Page 14: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 14

Example – Lamp (2)Example – Lamp (2)class Lamp {class Lamp {

protectedprotected boolean on; boolean on;

public Lamp(boolean initOn) { public Lamp(boolean initOn) {

on = initOn;on = initOn;

}}

public void pressSwitch() { public void pressSwitch() {

on = ! on;on = ! on;

}}

public void print() { public void print() {

System.out.println("Lamp("+onSystem.out.println("Lamp("+on

+")");+")");

}}

};};

class AdjLamp class AdjLamp extends Lampextends Lamp { { private double brightness;private double brightness;

public AdjLamp(boolean on) {public AdjLamp(boolean on) { super(on)super(on); ; }}

public void pressSwitch() { public void pressSwitch() { super.pressSwitch();super.pressSwitch(); brightness = 1.0;brightness = 1.0;

}}

public void dim() { public void dim() { if (brightness > 0.1)if (brightness > 0.1) brightness -= 0.1; brightness -= 0.1; }}

public void print()public void print() { { System.out.println("AdjLamp(“+System.out.println("AdjLamp(“+onon

+","+brightness+")");+","+brightness+")"); }}};};

enables visibility in subclasses

Page 15: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 15

Lamp Example - LessonsLamp Example - Lessons

Derived objects...Derived objects... extend extend their superclasstheir superclass

e.g. AdjLamp extends Lamp with dim() and brightnesse.g. AdjLamp extends Lamp with dim() and brightness inheritinherit all members of the superclass all members of the superclass

e.g. All AdjLamp objects have method pressSwitch() and e.g. All AdjLamp objects have method pressSwitch() and field onfield on

can can access access public and protected fields of the superclasspublic and protected fields of the superclass AdjLamp can access on and pressSwitchAdjLamp can access on and pressSwitch

can can overrideoverride methods of the superclass methods of the superclass AdjLamp print() overrides Lamp print()AdjLamp print() overrides Lamp print()

can can callcall public and protected methods of the superclass public and protected methods of the superclass super(on)super(on) super.pressSwitch() //more on this...super.pressSwitch() //more on this...

Note difference between inheritance and visibilityNote difference between inheritance and visibility! ! If CheapAdjLamp is a subclass of AdjLamp, its objects cannot If CheapAdjLamp is a subclass of AdjLamp, its objects cannot

access brightness even though they do have a brightness field.access brightness even though they do have a brightness field.

Page 16: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 16

SuperSuper

Used to call the constructor of a superclassUsed to call the constructor of a superclass can only be called from subclass constructor.can only be called from subclass constructor. must be called on the first line.must be called on the first line. can be called with different parameters according to the can be called with different parameters according to the

superclass constructor you wish to call.superclass constructor you wish to call. super(on);super(on); super();super(); super(arg1, arg2);super(arg1, arg2);

Used to call an overridden method from a Used to call an overridden method from a superclass.superclass. super.pressSwitch()super.pressSwitch()

Always calls a method in the immediate superclassAlways calls a method in the immediate superclass

Page 17: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 17

Inheritance: Watch ExampleInheritance: Watch Example

Watch

#_price:double#_model:String

+Watch(model:String,price:double)+setSalePrice():double

LuxuryWatch

#_premium:double

+LuxuryWatch(model:String,price:double,premium:double)+setSalePrice():double

public class Watch {public class Watch {

protected double _price;protected double _price; protected String _model;protected String _model;

public Watch(String model, public Watch(String model, double price) {double price) {

_model = model; _model = model; _price = price;_price = price;

}}

public double setSalePrice() {public double setSalePrice() { _price = _price* 0.80;_price = _price* 0.80; return _price; return _price; }}}}

Page 18: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 18

Inheritance: Watch Example (2)Inheritance: Watch Example (2)

public class LuxuryWatch extends Watch {public class LuxuryWatch extends Watch {

protected double _premium; protected double _premium; // ensures that sale prices are not too low // ensures that sale prices are not too low

public LuxuryWatch(String model, public LuxuryWatch(String model, double price, double premium) {double price, double premium) {

super(model,price);super(model,price); _premium = premium;_premium = premium; }}

public double setSalePrice() {public double setSalePrice() { return (super.setSalePrice() + _premium);return (super.setSalePrice() + _premium); }}}}

Page 19: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 19

Visibility Revisited: ProtectedVisibility Revisited: Protected

Remember Public and Private keywords?Remember Public and Private keywords? A new one: ProtectedA new one: Protected

Protected methods and fields can be accessed from the Protected methods and fields can be accessed from the class and subclasses.class and subclasses.

Less restrictive than private (only allows access from Less restrictive than private (only allows access from within class)within class)

More restrictive than public (allows everyone to access)More restrictive than public (allows everyone to access) E.g.E.g.

Subclass of AdjLamp cannot access fields brightness, Subclass of AdjLamp cannot access fields brightness, but can on.but can on.

Other classes cannot access either. Other classes cannot access either.

Page 20: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 20

Visibility: SummaryVisibility: Summary

publicpublic protectedprotected packagepackage

(default)(default)privateprivate

within within classclass

YesYes YesYes YesYes YesYes

within within packagepackage

YesYes YesYes YesYes NoNo

within within subclasssubclass

YesYes YesYes NoNo NoNo

AnywhereAnywhere YesYes NoNo NoNo NoNo

Page 21: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 21

Using Derived ClassesUsing Derived Classes

Derived classes are used exactly in the same way Derived classes are used exactly in the same way as normal classes.as normal classes.{...{...

AdjLamp l = new AdjLamp(true); AdjLamp l = new AdjLamp(true);

l.print();l.print();

l.dim();l.dim();

l.pressSwitch();l.pressSwitch();

...}...} In addition, if an adjustable lamp is a kind of lamp, In addition, if an adjustable lamp is a kind of lamp,

we can also do:we can also do:Lamp l = new AdjLamp(true); Lamp l = new AdjLamp(true);

However, there are some details we need to However, there are some details we need to discuss...discuss...

Page 22: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 22

Using Derived Classes: Using Derived Classes: PolymorphismPolymorphismpublic class Room {public class Room { private Lamp l;private Lamp l; public Room(Lamp l) {this.l = l;}public Room(Lamp l) {this.l = l;}

public void strobe(int pulses) {public void strobe(int pulses) { for (int i=0; i<= pulses; i++) {for (int i=0; i<= pulses; i++) { l.print();l.print(); l.pressSwitch();l.pressSwitch(); l.print();l.print(); l.pressSwitch();l.pressSwitch(); }} }}}}

Room

public void nightclub() {public void nightclub() {Room r = new Room(new Room r = new Room(new AdjLamp(false));AdjLamp(false));r.strobe(40);r.strobe(40);

}}

Which print()method gets called?

AdjLamp

+dim(): void+print():void

Lamp

+pressSwitch():void+print(): void

Page 23: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 23

Apparent and Actual typesApparent and Actual types

The The apparent typeapparent type of an object is that which the of an object is that which the compiler can statically infer. compiler can statically infer. e.g. e.g. Lamp l = … Lamp l = …

The The actual typeactual type is the type the object really has. is the type the object really has. e.g. e.g. new AdjLamp(…)new AdjLamp(…)

Rules Rules Apparent type must be super type of the actual typeApparent type must be super type of the actual type

e.g. e.g. AdjLamp l = new Lamp() //WRONG. Compile Error.AdjLamp l = new Lamp() //WRONG. Compile Error. Access methods and fields according to apparent typeAccess methods and fields according to apparent type

e.g. e.g. Lamp l; ... l.dim() //WRONG. Compile Error.Lamp l; ... l.dim() //WRONG. Compile Error.

Java checks these rules at compile time. Java checks these rules at compile time. It is a It is a strongly typedstrongly typed language language It does It does static type checking.static type checking.

Page 24: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 24

Late BindingLate Bindingpublic class Room {public class Room { private Lamp l;private Lamp l; public Room(Lamp l) {this.l = l;}public Room(Lamp l) {this.l = l;}

public void strobe(int pulses) {public void strobe(int pulses) { for (int i=0; i<= pulses; i++) {for (int i=0; i<= pulses; i++) { l.print();l.print(); l.pressSwitch();l.pressSwitch(); l.print();l.print(); l.pressSwitch();l.pressSwitch(); }} }}}}

public void nightclub() {public void nightclub() {Room r = new Room(new Room r = new Room(new AdjLamp(false));AdjLamp(false));r.strobe(40);r.strobe(40);

}}

At runtime, the JVM will access the object

(which has actual type AdjLamp), and call print() and

pressSwitch() accordingly

Late binding means that the bind between method call and the actual method

to be executed is at runtime

Room

AdjLamp

+dim(): void+print():void

Lamp

+pressSwitch():void+print(): void

Page 25: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 25

Binding and Typing issues: Binding and Typing issues: ExampleExamplepublic static void main(String[] args) {public static void main(String[] args) {

Lamp l = new Lamp(true); Lamp l = new Lamp(true); l.print();l.print();l.pressSwitch(); l.print();l.pressSwitch(); l.print();// l.dim(); // l.dim(); ERRORERRORSystem.out.println("Adjustable");System.out.println("Adjustable");AdjLamp adjL = new AdjLamp(false); AdjLamp adjL = new AdjLamp(false); adjL.print();adjL.print();adjL.pressSwitch();adjL.pressSwitch();

adjL.dim();adjL.dim();adjL.print();adjL.print();System.out.println("Assignment");System.out.println("Assignment");l = new AdjLamp(false); l = new AdjLamp(false); l.print();l.print();l.pressSwitch();l.pressSwitch();

l.print();l.print(); // l.dim(); // l.dim(); ERROR dim is not a method of class ERROR dim is not a method of class LampLamp};};

OUTPUTOUTPUT

Lamp( true)Lamp( true)Lamp( false)Lamp( false)

AdjustableAdjustable

AdjLamp( false, 1.0 ) AdjLamp( false, 1.0 )

AdjLamp( true, 0.9 ) AdjLamp( true, 0.9 ) AssignmentAssignment

AdjLamp( false, 1.0 ) AdjLamp( false, 1.0 )

AdjLamp( true, 1.0 ) AdjLamp( true, 1.0 )

Page 26: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 26

UpcastingUpcastingpublic class Room {public class Room { private Lamp l;private Lamp l; public Room(Lamp l) {this.l = l;}public Room(Lamp l) {this.l = l;}

public void strobe(int pulses) {public void strobe(int pulses) { for (int i=0; i<= pulses; i++) {for (int i=0; i<= pulses; i++) { l.print();l.print(); l.pressSwitch();l.pressSwitch(); l.print();l.print(); l.pressSwitch();l.pressSwitch(); }} }}}}

Room Lamp

AdjLamp

public void discoteque() {public void discoteque() {Room r = new Room(new Room r = new Room(new AdjLamp(false));AdjLamp(false));r.strobe(40);r.strobe(40);

}}

The process of treating the object of type AdjLamp

as if it were of type Lamp is called upcasting

upcasting is done automatically

upcasting

Page 27: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 27

Substitution PrincipleSubstitution Principle

In general, inheritance can be used when the In general, inheritance can be used when the (impure) (impure) substitution principlesubstitution principle holds: holds:

I can replace the generalised class with a more specialised I can replace the generalised class with a more specialised class, and the program will not break.class, and the program will not break.

Subclasses extend/change the behaviour of the superclass. Subclasses extend/change the behaviour of the superclass. Provides Provides flexibility flexibility but can also introduce but can also introduce runtime errorsruntime errors.. E.g. An amphibious car is an impure substitution of a car E.g. An amphibious car is an impure substitution of a car

(because it extends them, with aquatic capabilities)(because it extends them, with aquatic capabilities) Some people would argue that inheritance should only be Some people would argue that inheritance should only be

used when the used when the pure substitution principlepure substitution principle holds: holds: I can replace the specialised class with a more general class, I can replace the specialised class with a more general class,

and the program will not break.and the program will not break. More restrictiveMore restrictive Does not allow subclasses to extend their superclass, only Does not allow subclasses to extend their superclass, only

change the internal implementation. change the internal implementation. E.g. A car is a pure substitution of a PetrolCarE.g. A car is a pure substitution of a PetrolCar

Page 28: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 28

DowncastingDowncasting

If impure inheritance is used, then you may need If impure inheritance is used, then you may need to narrow the type of the apparent class to be to narrow the type of the apparent class to be able to call certain methods.able to call certain methods.

Room Lamp

AdjLamp

downcasting

public class Room {public class Room { private Lamp l;private Lamp l; public Room(Lamp l) {this.l = l;}public Room(Lamp l) {this.l = l;} public void dimStrobe(int pulses) {public void dimStrobe(int pulses) { for (int i=0; i<= pulses; i++) {for (int i=0; i<= pulses; i++) { for (int j=0; j<=10; j++) {for (int j=0; j<=10; j++) {

((AdjLamp) l).dim() ; //Downcasting((AdjLamp) l).dim() ; //Downcasting l.pressSwitch();l.pressSwitch(); }}

}} }}}}

Page 29: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 29

Downcasting: ExampleDowncasting: Examplepublic static void main(String[] args) {public static void main(String[] args) {

Lamp l = new AdjLamp(true); Lamp l = new AdjLamp(true); l.print();l.print();l.pressSwitch(); l.print();l.pressSwitch(); l.print();// l.dim(); // l.dim(); ERRORERRORSystem.out.println(“About to downcast”);System.out.println(“About to downcast”);AdjLamp adjL = (AdjLamp) l; //downcast AdjLamp adjL = (AdjLamp) l; //downcast adjL.print();adjL.print();adjL.pressSwitch();adjL.pressSwitch();

adjL.dim();adjL.dim();adjL.print();adjL.print();l = new Lamp(false); l = new Lamp(false); System.out.println(“About to downcast”);System.out.println(“About to downcast”);adjL = (AdjLamp) l;adjL = (AdjLamp) l;l.pressSwitch();l.pressSwitch();

l.print();l.print();}}

OUTPUTOUTPUT

AdjLamp( true, 1.0)AdjLamp( true, 1.0)AdjLamp( false, 1.0)AdjLamp( false, 1.0)

About to downcastAbout to downcast

AdjLamp( false, 1.0 ) AdjLamp( false, 1.0 )

AdjLamp( true, 0.9 ) AdjLamp( true, 0.9 )

About to downcastAbout to downcastClassCastExceptionClassCastException

Page 30: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 30

Downcasting: LessonsDowncasting: Lessons

DowncastingDowncasting or or narrowcastingnarrowcasting is an explicit type is an explicit type conversionconversion

Some downcasts cannot be verified at compile Some downcasts cannot be verified at compile time, and may produce run-time errors time, and may produce run-time errors (ClassCastException).(ClassCastException).

If we write If we write (t)v(t)v where where tt is a type and is a type and vv a variable a variable If the actual type of the object referenced by If the actual type of the object referenced by vv is is tt or a or a

subclass of subclass of tt then then (t)v(t)v returns a reference of type returns a reference of type tt to to the object referenced by the object referenced by vv

If not, Java raises a If not, Java raises a ClassCastExceptionClassCastException, which means , which means that the object pointed by that the object pointed by vv cannot be cast onto cannot be cast onto tt

Page 31: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 31

Downcasting: Bag Example (1/2)Downcasting: Bag Example (1/2)

class Thing {class Thing {public void print() { public void print() {

System.out.println("this is a something");System.out.println("this is a something"); }}}}

class Coin extends Thing {class Coin extends Thing {protected int _value; protected int _value;

public Coin(int val) { _value = val; }public Coin(int val) { _value = val; }public int getValue() { return _value; }public int getValue() { return _value; }public void print() public void print()

{ System.out.println( _value + { System.out.println( _value + " coin" ); } " coin" ); }

}}

Thing

+print():void

Coin

-_value:int

+getValue():int+print():void

Page 32: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 32

Downcasting: Bag Example (2/2)Downcasting: Bag Example (2/2)

class Bag {class Bag {

private Thing[] _things = new Thing[10]; private Thing[] _things = new Thing[10]; private int _index = 0; private int _index = 0;

public void add(Thing t) {public void add(Thing t) {_things[_index++] = t;_things[_index++] = t;

}}

public Thing remove1() {public Thing remove1() {_index--; _index--; Thing t = _things[_index];Thing t = _things[_index];_things[_index] = null; _things[_index] = null; return t; return t;

}}}}

public static void main(String[] public static void main(String[] args) {args) {

Bag b = new Bag(); Bag b = new Bag();

b.add(new Coin(5)); b.add(new Coin(5)); Thing t = b.remove1() ;Thing t = b.remove1() ;t.print(); t.print(); // 5 coin// 5 coin// // t.getValue(); t.getValue();

// compile error (obviously)// compile error (obviously)

Coin c = (Coin) t; Coin c = (Coin) t; c.getValue(); c.getValue(); // ok// ok

}}

Page 33: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 33

instanceofinstanceof

Used to discover the actual type of an object. Used to discover the actual type of an object. Use to avoid ClassCastExceptions:Use to avoid ClassCastExceptions:

Thing t = b.remove1() ;Thing t = b.remove1() ;......if (if (t instanceof Coint instanceof Coin) { ) { Coin c = (Coin) t; //Downcast only if t is a coin!Coin c = (Coin) t; //Downcast only if t is a coin!

c.getValue(); c.getValue(); }}

Use to introduce conditional behaviour in general:Use to introduce conditional behaviour in general:

public int lampValuator(Lamp l) {public int lampValuator(Lamp l) {if (l if (l instanceof AdjLamp)instanceof AdjLamp)

return 10;return 10;elseelse

return 5;return 5;} }

......

Page 34: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 34

Polymorphism SummaryPolymorphism Summary

PolymorphismPolymorphism refers to the ability to treat refers to the ability to treat uniformly structures which may have uniformly structures which may have more than one form. more than one form.

Related conceptsRelated concepts InheritanceInheritance Actual and Apparent typesActual and Apparent types Casting (up and down)Casting (up and down) Late bindingLate binding Pure and impure substitutionPure and impure substitution Static type checking and run-time casting Static type checking and run-time casting

errorserrors

Page 35: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 35

Printing Queue Class DiagramPrinting Queue Class Diagram

Document

#_content:String

Document(n:String, c:String)+equals(d:Document):boolean+getName():String+print():void

PDFDocument

PDFDocument(n:String, c:String)+print():void

MSWordDocument

MSWordDocument(n:String, c:String)+print():void

PSDocument

PSDocument(n:String, c:String)+print():void

#_name:String

Page 36: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 36

Printing Queue – Document Printing Queue – Document SuperclassSuperclass

public class Document {public class Document { protected String _name;protected String _name; protected String _content;protected String _content;

public Document (String n, String c) { _name = n; _content = c;}public Document (String n, String c) { _name = n; _content = c;}

public void print() { System.out.println(_content); }public void print() { System.out.println(_content); }

public String getName() {return _name; }public String getName() {return _name; }

public boolean equals(Document d) { //Note that content is public boolean equals(Document d) { //Note that content is ignoredignored

return(d.getName()).equals(_name); }return(d.getName()).equals(_name); }

}}

Page 37: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 37

Printing Queue – Document Printing Queue – Document Subclasses Subclasses public class MSWordDocument extends Document {public class MSWordDocument extends Document {

MSWordDocument (String n, String c) { super(n, c); }MSWordDocument (String n, String c) { super(n, c); }public void print() { System.out.println("MSWord->" + public void print() { System.out.println("MSWord->" +

_name); }_name); }}}

public class PDFDocument extends Document {public class PDFDocument extends Document {

PDFDocument(String n, String c) { super(n, c); }PDFDocument(String n, String c) { super(n, c); } public void print() { System.out.println("Acroread ->" + public void print() { System.out.println("Acroread ->" + _name);}_name);}}}

public class PSDocument extends Document {public class PSDocument extends Document {

PSDocument(String n, String c) { super(n, c); }PSDocument(String n, String c) { super(n, c); }public void print() { System.out.println("PSDocument->" + public void print() { System.out.println("PSDocument->" +

_name);}_name);}}}

Page 38: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 38

Printing Queue – Main()Printing Queue – Main()

public class PrintQueue {public class PrintQueue { private LinkedList _docList = new LinkedList();private LinkedList _docList = new LinkedList();

public void add(Document d) { _docList.add(d); }public void add(Document d) { _docList.add(d); } public void print() {public void print() { while (!_docList.isEmpty()) {while (!_docList.isEmpty()) { Document d = (Document) _docList.removeFirst();Document d = (Document) _docList.removeFirst(); d.print();d.print(); }} }}}} public static void main(String[] args) {public static void main(String[] args) {

PrintQueue p = new PrintQueue();PrintQueue p = new PrintQueue(); p.add(new MSWordDocument("Hello World.doc", p.add(new MSWordDocument("Hello World.doc",

“Hi!”));“Hi!”)); p.add(new PDFDocument("Lecture1.pdf”, p.add(new PDFDocument("Lecture1.pdf”, “Introduction”));“Introduction”)); p.add(new PSDocument(“Lecture2.ps“, p.add(new PSDocument(“Lecture2.ps“, “Inheritance”));“Inheritance”)); p.print();p.print(); }}

What is the output?

Page 39: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 39

Inheritance hierarchiesInheritance hierarchies

Student

PhdStudent MscStudentUndergrad

Staff

Academic Temporary

Lecturer Professor

CollegeMember

Note: Lecture inherits indirectly from Staff.

Note that the hierarchy need not be a comprehensive classification:

e.g. Readers are academics that are not lecturers nor professorse.g. Some researchers are not academic nor temporary staff

Page 40: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 40

The Object ClassThe Object Class

ObjectObject is THE superclass. is THE superclass. In Java everything is a subclass of Object. In Java everything is a subclass of Object. Being an Object subclass is not declared Being an Object subclass is not declared

explicitly! explicitly!

String Random... CollegeMember

Student StaffMember

java.lang.Object

... ...

Page 41: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 41

The Java Class HierarchyThe Java Class Hierarchy

Object

Class StringNumber

ShortLongFloatByte

also see Java Development Kit Documentation

Page 42: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 42

The Java Type HierarchyThe Java Type Hierarchy

Page 43: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 43

Multiple InheritanceMultiple Inheritance

In Java a class can only have one direct superclassIn Java a class can only have one direct superclass Some object oriented languages support multiple Some object oriented languages support multiple

inheritance: A class can have more than one direct inheritance: A class can have more than one direct superclass.superclass.

Java provides “interfaces” and interface Java provides “interfaces” and interface hierarchies to make up for it. //see later...hierarchies to make up for it. //see later...

PartTimePhDandResearcher

PhDStudent Researcher Pure or impure substitution?

Page 44: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 44

Some comments on inheritanceSome comments on inheritance Useful when used correctly!Useful when used correctly! Do not get carried away!Do not get carried away!

Think of the Think of the pure substitutabilitypure substitutability principle as a guideline... principle as a guideline... In practice you In practice you sometimes sometimes may need break guidelines...may need break guidelines...

using impure substitutability, using impure substitutability, or even non-substitutability (very exceptionally!) or even non-substitutability (very exceptionally!)

How to decide when to bend design rules?How to decide when to bend design rules? Practice and Experience...Practice and Experience... Common sense...Common sense... Reading good programmer’s code...Reading good programmer’s code... Reading on design...Reading on design...

Some examples to think aboutSome examples to think about Should PieSlice extend Circle?Should PieSlice extend Circle? Should CarParkingLot extend VehicleParkingLot?Should CarParkingLot extend VehicleParkingLot? Should Square extend Rectangle?Should Square extend Rectangle?

Page 45: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 45

A Square IS A Rectangle?A Square IS A Rectangle?

Rectangle

#height: int

+perimteter(): int

+setHeight():void

+setWidth():void

Square

#width: int

Rectangle r = new Square();Rectangle r = new Square();r.setHeight(2);r.setHeight(2);r.setWidth(3);r.setWidth(3);System.out.println(r.perimeter());System.out.println(r.perimeter());

+getHeight():int

+getWidth():int The answer is No!The answer is No!

A square is like a A square is like a rectangle. rectangle.

This is impure This is impure substitution substitution

The “IS A” relation in OO is refers to visible The “IS A” relation in OO is refers to visible behaviour.behaviour.

Page 46: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 46

Debate on pure substitutabilityDebate on pure substitutability

In principle, A should be a subclass of B only ifIn principle, A should be a subclass of B only if the the pure substitutabilitypure substitutability principle holds... principle holds... A “is a” BA “is a” B

Does this hold for Square and Rectangle?Does this hold for Square and Rectangle? i.e. a Square “is a” Rectangle?i.e. a Square “is a” Rectangle? i.e. Is the behaviour of square like that of a rectangle?i.e. Is the behaviour of square like that of a rectangle? i.e. If I think I am operating on an object I believe is of i.e. If I think I am operating on an object I believe is of

class Rectangle, but it turns out to be of class square; class Rectangle, but it turns out to be of class square; would I notice the difference?would I notice the difference?

Page 47: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 47

A Square IS A Rectangle?A Square IS A Rectangle?

Rectangle

#height: int

+area(): int

+setHeight():void

+setWidth():void

Square

#width: int

Rectangle r = new Square();Rectangle r = new Square();r.setHeight(2);r.setHeight(2);r.setWidth(3);r.setWidth(3);System.out.println(r.perimeter());System.out.println(r.perimeter());

+getHeight():int

+getWidth():int The answer is No!The answer is No!

A square is like a A square is like a rectangle. rectangle.

This is impure This is impure substitution substitution

The “IS A” relation in OO is refers to visible The “IS A” relation in OO is refers to visible behaviour.behaviour.

Page 48: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 48

Using inheritance…Using inheritance…

Useful when used correctly!Useful when used correctly! Do not get carried away!Do not get carried away!

Real systems rarely have deep inheritance Real systems rarely have deep inheritance hierarchieshierarchies

Try to use Try to use pure substitutabilitypure substitutability as a guideline... as a guideline... However, in practice you these guidelines are However, in practice you these guidelines are

broken…broken… How to decide when to bend design rules?How to decide when to bend design rules?

Practice and Experience...Practice and Experience... Common sense...Common sense... Reading good programmer’s code...Reading good programmer’s code... Reading on design...Reading on design...

Page 49: 03 - Inheritance and Polymorphism. 2 © S. Uchitel, 2004 Modelling (1/2) A model should be an abstract yet precise description of a system. A model should

© S. Uchitel, 2004 49

ChecklistChecklist

UML and modellingUML and modelling Class relationships: Dependency, Association, Class relationships: Dependency, Association,

Aggregation, Composition and InheritanceAggregation, Composition and Inheritance Keywords Keywords supersuper and and extendsextends Visibility: public, private, Visibility: public, private, protectedprotected and default (package) and default (package) ““Is-a” vs. “Is-a-kind-of”.Is-a” vs. “Is-a-kind-of”. PolymorphismPolymorphism Actual and Apparent typesActual and Apparent types Late binding, Static type checking and Late binding, Static type checking and

ClassCastExceptionsClassCastExceptions Casting (up and down)Casting (up and down) instanceofinstanceof Pure and impure substitutionPure and impure substitution Class hierarchies and the Object class.Class hierarchies and the Object class.