Inheritance
Horstmann ch. 6.1.7-6.6, 6.9
Inheritance
- Inheritance
– reminder from dIntProg – pre- postconditions
- Graphics programming with inheritance
– extending JComponent – Mouse(Motion)Adapters – Abstract classes and TEMPLATE pattern – Refactoring
- Class hierarchies
– Swing – Geometric shapes – Exceptions
- When not to use inheritance
Inheritance
- concepts (from dIntProg)
– subclass specializes super class ... extends ... – inheritance hierarchies – overriding method – invoke super class method: super.methodname() – invoke super class constructor: super(...) – substitution principle
- overridden methods and pre/postconditions
– preconditions of redefined method at most as strong – postconditions of redefined method at least strong
Inheritance Hierarchy
Manager is subclass of Employee (though manager is superior to most employees)
The Substitution Principle
- Formulated by Barbara Liskov
- You can use a subclass object whenever a
superclass object is expected
- Example:
Employee e; ... System.out.println("salary=" + e.getSalary());
- Can set e to Manager reference
- Polymorphism: Correct getSalary method is
invoked
Preconditions
- Precondition of redefined method at most as strong
- public class Employee {
/** Sets the employee salary to a given value. @param aSalary the new salary @precondition aSalary > 0 */ public void setSalary(double aSalary) { ... } }
- Can we redefine Manager.setSalary with precondition
salary > 100000?
- No--Could be defeated:
Manager m = new Manager(); Employee e = m; e.setSalary(50000);