inheritance and polymorphism
DESCRIPTION
Inheritance and Polymorphism. Repetition from chapter 4page 2-3 Generalization og specializationpage 4-5 Inheritancepage 6-7 Polymor p hismpage 8-10 The renovation casepage 11-12 What if polymor p hism didn't exist?page 13 When do we need instanceof?page 14 - PowerPoint PPT PresentationTRANSCRIPT
versjon 2002-04-17Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12
Java the UML Wayhttp://www.tisip.no/JavaTheUmlWay/
Inheritance and Polymorphism
Repetition from chapter 4 page 2-3Generalization og specialization page 4-5Inheritance page 6-7Polymorphism page 8-10The renovation case page 11-12What if polymorphism didn't exist? page 13When do we need instanceof? page 14Access modifiers page 15-17Two levels of inheritance page 18Rules and definitions page 19-24Interface page 25-28
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 2
A Segment of the Java Class Tree
Object
Component
Container
Panel
Applet
JApplet
JComponent
JPanel
SimpleApplet
Drawing
setBackground() and getBackground() are inherited from here
add() is inherited from here
the superclassfor all other classes
the superclass forJPanel and Drawing
the subclass forObject and Component
From chapter 4
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 3
From chapter 4
The Objects the Different Classes Describe Form Sets
Container
JComponent Panel
Applet
JApplet
SimpleApplet
JPanel
Drawing
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 4
Generalization and Specialization
specializations,subclasses
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 5
What Tells the Class Tree?
Material
WallpaperPaintFlooring
A flooring is a material.A paint is a material.A wallpaper is a material.
All floorings make a subsetof all materials.All paints make a subsetof all materials.All wallpapers make a subset of all materials.
A class tree shows a relationship between classes.A class is a generalization/specialization of another class.The arrow has the direction from the specialized class to the generalized class.
Don't confuse associations with generalization/specialization! An association between two classes means that there is a connection between the objects in the two classes.
Solve the problem,page 342.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 6
Inheritance
• A subclass inherits non-private members for the suberclass.
• Examples: A client may send the following messages to a Flooring object:
– getName()
– getPricePerUnit()
– getTotalPrice()
– getWidth()
– getMaterialReq()
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 7
What About the (Private) Data in the Superclass?
• An instance of the Wallpaper class has the instance variables from the Material class (name and price) as part of itself, but they may only be accessed via methods inherited from Material.
Brocade500120.6
Wallpaper theWallpaper = new Wallpaper ("Brocade", 500, 12, 0.6);
can only be accessed via get methods
private in the Wallpaper class
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 8
Polymorphism• The formulas for calculating the material requirement
is different for flooring, paint and wallpaper.• It is possible to calculate the requirement for every
type of material.• The getMaterialReq() is polymorphous (= ” the quality
or state of being able to assume different forms”).• The method is abstract in the Material class (it is not
possible to state one common formula for all types of materials).
• The class is abstract because it contains (at least) one abstract method.
• It is not possible to instantiate objects of an abtract class.
• To be able to create instances of a subclass, this subclass needs to have an implementation of the getMaterialReq() method. The class is concrete.
• The fact that getMaterialReq() is an (abstract) method in the Material class tells that it is possible to send the getMaterialReq() message to every object which is an instance of a concrete subclass of the Material class.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 9
Solve the problems, pp. 344-345.
double area = aSurface.getArea();double noOfLiters = area * noOfCoats / noOfSqMPerLiter;int noOfLitersInteger = (int) noOfLiters;double more = noOfLiters - noOfLitersInteger;if (more >= 0.5 + limit) return noOfLitersInteger + 1.0;else if (more >= limit) return noOfLitersInteger + 0.5;else return noOfLitersInteger;
double lengthSurface = aSurface.getLength();double heightSurface = aSurface.getWidth();/* calculate the number of heights */int noOfHeights = (int) (lengthSurface / widthPerRoll);double remnant = lengthSurface % widthPerRoll;if (remnant >= limit) noOfHeights++;/* calculate the number of rolls */int noOfRolls;int noOfHeightsPerRoll = (int) (lengthPerRoll / heightSurface);if (noOfHeightsPerRoll > 0) { noOfRolls = noOfHeights / noOfHeightsPerRoll; remnant = noOfHeights % noOfHeightsPerRoll; if (remnant >= limit) noOfRolls++;} else { // the roll is shorter than one height (rarely!)
client
getMaterialReq(theSurface)
getMaterialReq(theSurface)
getMaterialReq(theSurface)
aPaint
aFlooring
aWallpaper
double lengthSurface = aSurface.getLength();double widthSurface = aSurface.getWidth();int noOfWidths = (int)(lengthSurface / widthOfFlooring);double remnant = lengthSurface % widthOfFlooring;if (remnant >= limit) noOfWidths++;return noOfWidths * widthSurface;
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 10
Show Program Listing 12.1 (pp. 346-349) and 12.2 (pp. 351-352).
Solve the Problems 2-4, pp. 350-351. Solve the Problems 1, 3 and 4, pp. 353-354.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 11
Class Diagram for Renovation Project with Many Surfaces and Many Materials
Flooring
-widthOfFlooring {frozen}
+getMaterialReq(aSurface: Surface)
Wallpaper
-lengthPerRoll {frozen}-widthPerRoll {frozen}+getMaterialReq(
aSurface: Surface)
Paint
-noOfCoats {frozen}-noOfSqMPerLiter {frozen}
+getMaterialReq(aSurface: Surface)
Materiale
-name {frozen}-price {frozen}
+getTotalPrice(aSurface: Surface)+getMaterialReq(aSurface: Surface)
Surface
+setMaterial(newMaterial: Material)
+getMaterial()+getArea()+getCircumference()
-name {frozen}-length {frozen}-width {frozen}
*1
*1
needs
consists of
1
*
uses
Material
RenovationProject
name: String {frozen}
getName()addNewSurface(
newSurface: Surface)getSurface(name: String)getNoOfSurfaces()getSurface(index: int)addNewMaterial(
newMaterial: Material)getMaterial(name: String)getNoOfMaterials()getMaterial(index: int)getTotalPrice()
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 12
The Renovation Project with Many Surfaces and Many Materials, Coding the Program
From chapter 10:class RenovationProject {
private String name;
private ArrayList allSurfaces = new ArrayList();
private ArrayList allPaints = new ArrayList();
public Paint addNewPaint(Paint newPaint) {
Paint thisPaint = getPaint(newPaint.getName());
if (thisPaint == null) {
allPaints.add(newPaint);
return newPaint;
}
else return thisPaint;
}
Now, in chapter 12:class RenovationProject {
private String name;
private ArrayList allSurfaces = new ArrayList();
private ArrayList allMaterials = new ArrayList();
public Material addNewMaterial(Material newMaterial) {
Material thisMaterial = getMaterial(newMaterial.getName());
if (thisMaterial == null) {
allMaterials.add(newMaterial);
return newMaterial;
}
else return thisMaterial;
A reference to Material may be set to refer to an instance of a subclass of Material.
Our new version of the renovation program may handle many different materials, in spite of very few changes from the former version. We make the most of inheritance og polymorphism.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 13
What If Polymorphism Didn't Exist?• What does polymorphism do for us?
– In this example, it lets us handle different types of materials as a whole. – We send the message getMaterialReq() to an object that is an instance of a subclass of
Material.– The object itself knows how it should calculate the materials needed.
• What if the objects themselves didn’t know how the need should be calculated? – Then somewhere or other we would have had to make an if-else-if-else sequence (something
like this): if (material instanceof Paint) { ....formulas for calculating paint requirements } else if (material instanceof Flooring) { ....formulas for calculating covering requirements } else { ....formulas for calculating wallpaper requirements }
• Consider one more time if you think you need to use instanceof combined with an if-else-if-else sequence.
– To do this, evaluate if it is better to make an abstract method in a common superclass for the classes involved and thus let every individual class get its own implementation for the method.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 14
When Do We Need to Use the Operator instanceof?
• We need to use instanceof in conjunction with class trees in those cases where we will send a message to only one part of a subtree.• We create the following objects:
A object1 = new C();A object2 = new E();
• We can safely send the message method1() to both of the objects:object1.method1();object2.method1();
• We can only send the message method2() to subclasses of the class B.
if (object1 instanceof B) { B anObject = (B) object1; anObject.method2();}
A
DCB
FE
method1() abstract in A
method2() abstract in B
method1() implemented here
method2() implemented here
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 15
Access Modifiers
• The scope of a name is the part of the program where the name may be used without qualifying it.
• The accessibility for a name outside its scope is determined by the access modifier (private, public, protected or nothing, nothing = package) placed in front of the name.
• Classes:– All classes up to now, except for
the applets, have been accessible only in the package where they were declared (package access).
– The applets have public access. They are accessible from everywhere.
• Members and constructors:– private int number;
– protected int getMinimumValue() { // accessible from the same package// and from subclasses (under // certain conditions)
– public int getNumber() {
– int getSecretNumber() { // package access
• Class access overrides member/constructor access:
– Example: For a member (or a constructor) to have public access, both the member (or the constructor) and the class must be declared public.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 16
The Access for Constructors and Members Declared in the Class C
package A package B
class C subclass to class Cprivate
package*
protected
public
*) package means no access modifier
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 17
Recommended Use of Access Modifiers
• Instance variables and class variables are always private.
• Constants are usually public, but can be private if they are not of interest outside the class.
• Constructors are usually public.
• Methods are usually private or public.
• Constructors and methods can be protected if there is no point in using them outside subclasses.
• About classes:– As a point of departure, classes have package access (no access modifier).
This also limits the access to public constructors and members of the class.
– Classes that will be taken into general use are made public and added to a named package. Then all public constructors and members will also automatically become public.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 18
Flooring2
- widthOfFlooring
+ getWidth()+ getMaterialReq(aSurface: Surface)
Material
-name-price
+getName()+getPricePerUnit()+getTotalPrice(aSurface: Surface)+getMaterialReq(aSurface: Surface)
FirstSortFlooringSecondSortFlooring
+getTotalPrice(aSurface: Surface)+getMaterialReq(aSurface:Surface)
Wallpaper
-lengthPerRoll-widthPerRoll
+getLengthPerRoll()+getWidthPerRoll()+getMaterialReq(
aSurface: Surface)
Paint
-noOfCoats-noOfSqMPerLiter
+noOfCoats()+noOfSqMPerLiter() +getMaterialReq(
aSurface: Surface)
Two Levels of Inheritance
Show program listing 12.4 pp. 365-367.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 19
The abstract Modifier
• An abstract class:abstract class Material {
….etc.
– cannot insantiate objects of an abstract class
– may or may not contain or inherit sbtract methods
– may contain both abstract and concrete methods
• An abstract method:abstract method head;
– A class that inherits, or declares on its own, an abstract method, has to be declared abstract.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 20
The super Keyword
• super can be used in two ways:– In a constructor to invoke the constructor in the direct superclass, for
example:public SecondSortFlooring(String initName, double initPrice, double initWidth) {
super(initName, initPrice, initWidth);
}
• The call to super() has to be the first statement in the constructor body.
• The arguments to super() must be in accordance with the parameter list of one of the constructors in the direct superclass.
– In a method we may use super as a qualifier to refer to a hidden or overriden name in a superclass, for example:
public double getMaterialReq(Surface aSurface) {
double basicReq = super.getMaterialReq(aSurface);
return basicReq * materialAddendum;
}
• We cannot write super.super() or something like that, to refer to a constructor or a method more than one level above in the class tree.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 21
Constructors
• If we don’t call a specific constructor in the direct superclass by calling super(), a constructor with no arguments will be called.
• If this doesn’t exist, the compiler will give an error message.
• If the intent is not to make instances of a class, this can be prevented in two ways:– Make the class abstract. This is used if the class has or can have
subclasses.
– Make all constructors private. This is used if the class cannot have subclasses (it is final, see slide 23).
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 22
References and Casting
• Assume that all the classes in the figure are concrete.• A reference to a class can be set to point to instances of a subclass to the class.
It cannot be set to point to instances of a superclass. Examples:Material aMaterial = new FirstSortFlooring("SuperDuper", 140, 5); // okFirstSortFlooring fineFlooring = new SecondSortFlooring("SuperDuper2", 140, 6); // not okFirstSortFlooring veryFineFlooring = new Flooring2("SuperDuper1", 140, 5); // not ok
• Assume that we have a reference to an object. – The reference can be cast to the class the object is an instance of, or to superclasses
of this class. – It’s not allowed to cast the reference to a subclass of the class that the object is an
instance of. – Invalid casting gives a ClassCastException. Examples:
Object anObject = new Flooring2("SuperDuper", 140, 5); // okFlooring2 aFlooring = (Flooring2) anObject; // okFirstSortFlooring fineFlooring = (FirstSortFlooring) aFlooring; // not okFirstSortFlooring veryFineFlooring = (FirstSortFlooring) anObject; // not ok
Flooring2
SecondSortFlooringFirstSortFlooring
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 23
The final Modifier
• final prevents subclassing and overriding.
• A final method cannot be overridden nor hidden:public final double getWidth() {
return widthOfFlooring;
}
• It is not possible to subclass a final class:final class SecondSortFlooring extends Flooring2 {
….osv.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 24
Overriding or Hiding a Name
• Overriding an inherited instance method– If a class declares an instance method, this declaration will override any
inherited method there might be with the same signature. – The compiler gives an error message if the return type is not right and/or
the level of access is less strict than in the overridden method. – An instance method cannot override an inherited class method.
• We may hide inherited names of variables and class methods. We do not use this in this book.
class SecondSortFlooring extends Flooring2 { ….. public double getMaterialReq(Surface aSurface) { double basicReq = super.getMaterialReq(aSurface); return basicReq * materialAddendum; }}
This method replaces the inherited version of the getMaterialReq()
method Here we refer to the method which is replaced with the
new version.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 25
InterfaceRepetition from chapter 10.
• An interface, simply put, is a collection of method heads. • A class can choose to implement an interface. Then all the methods in the
interface have to be programmed. • An example from the java.lang package is:
public interface Comparable { public int compareTo(Object obj);}
• Example of a class implementing this interface:class Surface implements Comparable { public int compareTo(Object obj) { // comparing areas
Surface theOtherSurface = (Surface) obj;double area1 = getArea(); // the area of thisdouble area2 = theOtherSurface.getArea();if (area1 < area2 - 0.0001) return -1; // comparing decimal numeralselse if (area1 > area2 + 0.0001) return 1;else return 0;
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 26
To Create Your Own Interfaces
interface MyComparable { boolean greaterThan(Object obj); boolean lessThan(Object obj); boolean equal(Object obj);}
interface Constants { int min = 1000; int max = 9999;}
Access modifierpublic or nothing (package access)
public abstract implied for methods
public static final implied for variables
An interface is abstract.It is not possible toinstantiate objects ofan interface.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 27
Implementation of Interfaces
class FourDigitsNumber implements Constants, MyComparable { private int value; public FourDigitsNumber(int initValue) { if (initValue < min) value = min; else if (initValue > max) value = max; else value = initValue; } public int getValue() { return value; } public boolean greaterThan(Object obj) { FourDigitsNumber number = (FourDigitsNumber) obj; return (value > number.getValue()); } public boolean lessThan(Object obj) { FourDigitsNumber number = (FourDigitsNumber) obj; return (value < number.getValue()); } public boolean equal(Object obj) { FourDigitsNumber number = (FourDigitsNumber) obj; return (value == number.getValue()); }}
The class may use all constants declared in the Constants interface.
The class must have animplementation of every method in the MyComparableinterface, or it will be abstract.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 12, page 28
Using the FourDigitsNumber Class
• A reference of an interface type may refer to instances of classes that implements the interface:
– FourDigitsNumber number1 = new FourDigitsNumber(700);– FourDigitsNumber number2 = new FourDigitsNumber(1700);
• No other messages than those declared in the interface may be sent to the object:– System.out.println(number1.greaterThan(number2)); // ok– System.out.println(number1.getValue()); // not ok
class ExInterface { public static void main(String[] args) { FourDigitsNumber number1 = new FourDigitsNumber(700); FourDigitsNumber number2 = new FourDigitsNumber(1700); FourDigitsNumber number3 = new FourDigitsNumber(70000); System.out.println(number1.getValue()); System.out.println(number2.getValue()); System.out.println(number3.getValue()); System.out.println(number1.greaterThan(number2)); System.out.println(number1.lessThan(number2)); System.out.println(number1.equal(number2)); }}
/* Example Run:100017009999falsetruefalse*/