1 / 28

Inheritance and Polymorphism

Inheritance and Polymorphism. Repetition from chapter 4 page 2-3 Generalization og specialization page 4-5 Inheritance page 6-7 Polymor p hism page 8-10 The renovation case page 11-12 What if polymor p hism didn't exist? page 13 When do we need instanceof? page 14

Download Presentation

Inheritance and Polymorphism

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Inheritance and Polymorphism Repetition from chapter 4 page 2-3 Generalization og specialization page 4-5 Inheritance page 6-7 Polymorphism page 8-10 The renovation case page 11-12 What if polymorphism didn't exist? page 13 When do we need instanceof? page 14 Access modifiers page 15-17 Two levels of inheritance page 18 Rules and definitions page 19-24 Interface 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  2. the superclass for all other classes Object From chapter 4 setBackground() and getBackground() are inherited from here A Segment of the Java Class Tree Component the subclass for Object and Component Container add() is inherited from here the superclass for JPanel and Drawing JComponent Panel JPanel Applet Drawing JApplet SimpleApplet 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  3. The Objects the Different Classes Describe Form Sets From chapter 4 Container Panel JComponent JPanel Applet JApplet Drawing SimpleApplet 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  5. What Tells the Class Tree? Material All floorings make a subset of all materials. All paints make a subset of all materials. All wallpapers make a subset of all materials. A flooring is a material. A paint is a material. A wallpaper is a material. Flooring Paint Wallpaper Solve the problem, page 342. A class tree shows a relationship betweenclasses. 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. 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 methodsinherited from Material. Brocade 500 12 0.6 can only be accessed via get methods private in the Wallpaper class Wallpaper theWallpaper = new Wallpaper ("Brocade", 500, 12, 0.6); 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  8. 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. Polymorphism • 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  9. 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; getMaterialReq(theSurface) aPaint double lengthSurface = aSurface.getLength(); double widthSurface = aSurface.getWidth(); int noOfWidths = (int)(lengthSurface / widthOfFlooring); double remnant = lengthSurface % widthOfFlooring; if (remnant >= limit) noOfWidths++; return noOfWidths * widthSurface; getMaterialReq(theSurface) aFlooring getMaterialReq(theSurface) client 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!) aWallpaper Solve the problems, pp. 344-345. 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  11. Class Diagram for Renovation Project with Many Surfaces and Many Materials 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  12. 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 MaterialaddNewMaterial(Material newMaterial) { Material thisMaterial = getMaterial(newMaterial.getName()); if (thisMaterial == null) { allMaterials.add(newMaterial); return newMaterial; } else return thisMaterial; The Renovation Project with Many Surfaces and Many Materials, Coding the Program 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 itselfknows 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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(); } method1() abstract in A A method2() abstract in B B C D E F 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  15. 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. Access Modifiers 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  16. The Access for Constructors and Members Declared in the Class C package A package B class C subclass to class C private 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  18. 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  22. References and Casting Flooring2 • 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); // ok FirstSortFlooring fineFlooring = new SecondSortFlooring("SuperDuper2", 140, 6); // not ok FirstSortFlooring 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); // ok Flooring2 aFlooring = (Flooring2) anObject; // ok FirstSortFlooring fineFlooring = (FirstSortFlooring) aFlooring; // not ok FirstSortFlooring veryFineFlooring = (FirstSortFlooring) anObject; // not ok FirstSortFlooring SecondSortFlooring 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  25. Repetition from chapter 10. Interface • 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 this double area2 = theOtherSurface.getArea(); if (area1 < area2 - 0.0001) return -1; // comparing decimal numerals else 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  26. To CreateYour Own Interfaces Access modifier public ornothing (package access) interface MyComparable { boolean greaterThan(Object obj); boolean lessThan(Object obj); boolean equal(Object obj); } interface Constants { int min = 1000; int max = 9999; } public abstract implied for methods public static final implied for variables An interface is abstract. It is not possible to instantiate objects of an 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 /* Example Run: 1000 1700 9999 false true false */ 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)); } } 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

More Related