inheritance inheritance basic concepts
play

Inheritance Inheritance: basic concepts subclass specializes super - PDF document

Horstmann ch. 6-6.6, 6.9 Inheritance Inheritance: basic concepts subclass specializes super class: extends inheritance hierarchies overriding method invoke super class method: super.methodname() invoke super class


  1. Horstmann ch. 6-6.6, 6.9 Inheritance

  2. Inheritance: basic concepts • subclass specializes super class: … extends … • inheritance hierarchies • overriding method • invoke super class method: super.methodname() • invoke super class constructor: super(…) • substitution principle

  3. Modeling specialization public class Manager extends Employee { public Manager(String aName) {...} public void setBonus(double aBonus) { bonus = aBonus; } public double getSalary() {...} private double bonus; } New field New method

  4. Manager is subclass of Employee • Why is Manager a sub class? • Isn't a Manager superior? • Doesn't a Manager object have more fields? • The set of managers is a subset of the set of employees

  5. Inheritance Hierarchy • Real world: Hierarchies describe general/specific relationships – General concept at root of tree – More specific concepts are children • Programming: Inheritance hierarchy – General superclass at root of tree – More specific subclasses are children

  6. public class Employee { QUIZ private int salary; public void setSalary(int n) Inheritance { salary = n; } } Which lines are legal? public class Volunteer extends Employee { 1. none private int charity; 2. A public void setCharity(int n) 3. B { charity = n; } 4. A,B } 5. I don’t know Employee e = new Employee(); e.setSalary(100); e.setCharity(50); A Volunteer v = new Volunteer(); B v.setSalary(10); v.setCharity(5);

  7. The Substitution Principle • You can use a subclass object whenever a superclass object is expected • Example: Employee e; e = new Employee(”Axel”); or e = new Manager(”Bent”); ... or ... System.out.println("salary=" + e.getSalary()); • Polymorphism: Correct getSalary method is invoked

  8. QUIZ Inheritance and Polymorphism getInterest() in class Account: return getBalance() * 0.01; getInterest() in class ShareHolderAccount return getBalance() * 0.02; Application: ShareHolderAccount sh = new ShareHolderAccount(100); System.out. print ln(sh.getinterest()); What is printed? 1. 1.0 and 1.0 Account ac = new ShareHolderAccount(100); 2. 1.0 and 2.0 System.out. print ln(ac.getinterest()); 3. 2.0 and 1.0 4. 2.0 and 2.0 5. I don’t know

  9. Invoking Superclass Methods • Can't access private fields of superclass public class Manager extends Employee { public double getSalary() { return salary + bonus; } ... Error: salary is private } • Be careful when calling superclass method public double getSalary() { return getSalary() + bonus; } Error: recursive call

  10. Invoking Superclass Methods • Use super keyword public double getSalary() { return super. getSalary() + bonus; } • super is not a reference • super turns off polymorphic call mechanism

  11. Invoking Superclass Constructors • Use super keyword in subclass constructor: public Manager(String aName) { super(aName); bonus = 0; } Calls superclass constructor: public Employee(String na) { name = na; } • Call to super must be first statement in subclass constructor • If subclass constructor doesn't call super , superclass must have constructor without parameters

  12. public class Volunteer extends Employee { public int getSalary() { QUIZ return ; } Turn off polymorphism …} Which lines may replace if we want to return salary-charity ? 1. None, 2. a 3. b 4. c 5. a,b 6. a,c a) salary - charity 7. b,c b) getSalary() – charity 8. a,b,c c) super.getSalary() - charity 9. I don’t know

  13. Inheritance: more concepts • Refactoring • Abstract class • Template Pattern • Protected access

  14. Scene Editor • Draws various shapes • User can add, delete, move shapes • User selects shape with mouse • Selected shape is highlighted (filled in)

  15. The SceneShape Interface Type • keep track of selection state • draw plain or selected shape • move shape • hit testing : is a point (e.g. mouse position) inside? • public interface SceneShape { void setSelected(boolean b); boolean isSelected(); void draw(Graphics2D g2); void drawSelection(Graphics2D g2); void translate(int dx, int dy); boolean contains(Point2D aPoint); }

  16. CarShape and HouseShape Classes public class CarShape implements SceneShape { ... public void setSelected(boolean b) { selected = b; } public boolean isSelected() { return selected; } private boolean selected; } public class HouseShape implements SceneShape { ... public void setSelected(boolean b) { selected = b; } public boolean isSelected() { return selected; } private boolean selected; }

  17. Inheritance: more concepts • Refactoring • Abstract class • Template Pattern • Protected access

  18. Abstract Classes • Factor out common behavior ( setSelected, isSelected ) • Subclasses inherit common behavior • Some methods still undefined ( draw, drawSelection, translate, contains ) public abstract class SelectableShape implements SceneShape { public void setSelected(boolean b) { selected = b; } public boolean isSelected() { return selected; } private boolean selected; }

  19. HouseShape and CarShape are • concrete • Can't instantiate abstract class: SelectableShape s = new SelectableShape(); // NO • Ok to have variables of abstract class type: SelectableShape s = new HouseShape(); // OK

  20. Abstract Classes and Interface Types • Abstract classes can have fields • Interface types can only have constants – public static final int MAXIMUM = 1000; • Abstract classes can both define and declare methods – Define: public int getValue() { return value; } – Declare: public abstract int getValue(); • Interface types can only declare methods – public int getValue(); • A class can implement any number of interface types • In Java, a class can extend only one other class

  21. public abstract class Account { QUIZ private int balance; public abstract int computeFee(); Abstract class/method public int getInterest() { return 0; } } Which public class SavingsAccount extends Account implementations A { public int computeFee(); } of SavingsAccount are legal? public class SavingsAccount extends Account B 1. None { } 2. A 3. B public class SavingsAccount extends Account { 4. C public int computeFee() { 5. A,B return getInterest()/2; C 6. A,C } 7. B,C } 8. A,B,C 9. I don’t know

  22. Inheritance: more concepts • Refactoring • Abstract class • Template Pattern • Protected access

  23. Uniform Highlighting Technique

  24. Uniform Highlighting Technique public void drawSelection(Graphics2D g2) { translate(1, 1); draw(g2); translate(1, 1); draw(g2); translate(-2, -2) } drawSelection calls draw • draw not implemented yet! • • Declare as abstract method public abstract void draw(Graphics2D g2); • Defined in CarShape , HouseShape drawSelection method calls draw, translate • drawSelection doesn't know which methods -- • polymorphism drawSelection is a template method •

  25. TEMPLATE METHOD Pattern Context • An algorithm is applicable for multiple types. • The algorithm can be broken down into primitive operations . The primitive operations can be different for each type • The order of the primitive operations doesn't depend on the type Solution • Define a superclass that has a method for the algorithm and abstract methods for the primitive operations. • Implement the algorithm to call the primitive operations in the appropriate order. • Do not define the primitive operations in the superclass, or define them to have appropriate default behavior. • Each subclass defines the primitive operations but not the algorithm.

  26. TEMPLATE METHOD Pattern

  27. TEMPLATE METHOD Pattern EXAMPLE SelectableShape drawSelection() draw() translate() CarShape draw() translate()

  28. QUIZ Template method Which exemplifies Template Method pattern? Method playGame: 1. a a) init(); 2. b while (!done()) move(); 3. a+b 4. None 5. I don’t know Method playGame: b.init(); b) while (!b.done()) b.move();

  29. Inheritance: more concepts • Refactoring • Abstract class • Template Pattern • Protected access

  30. Compound Shapes • House = rectangle + triangle • Car = rectangle + circles + lines • CompoundShape uses GeneralPath • java.awt.geom.GeneralPath : sequence of shapes GeneralPath path = new GeneralPath(); path.append(new Rectangle(...), false); path.append(new Triangle(...), false); g2.draw(path); • Advantage: Containment test is free path.contains(aPoint);

  31. Access to Superclass Features • Why does the HouseShape constructor call add? public HouseShape() { add(new Rectangle(...)); add(new Triangle(...)); } • Why not just path.append(new Rectangle(...)); • HouseShape inherits path field • HouseShape can't access path • path is private to superclass

  32. Protected Access • Make CompoundShape.add method protected • Protects HouseShape : other classes can't add graffiti • Protected features can be accessed by subclass methods... • ...and by methods in the same package • Bad idea to make fields protected protected GeneralPath path; // DON'T • Ok to make methods protected protected void add(Shape s) // GOOD • Protected interface separate from public interface

  33. Inheritance: Examples • Graphics programming • Mouse(Motion)Listener • Class hierarchy examples

Recommend


More recommend