Self-check questions
Write your answers first, then open the answers to check them.
- What does "is-a" mean? Give two examples.
- Why does Java not allow a class to extend two classes? How is multiple inheritance achieved?
- Difference between overloading and overriding (three points).
- In what order do constructors run in a hierarchy?
Show answers
"Is-a" means the subclass is a more specialised kind of the superclass, so it can be used anywhere the superclass is expected. Examples: a Dog is an Animal; a Car is a Vehicle; a Manager is an Employee.
Extending two classes can cause the diamond problem: if both parents have the same method with different code, it is unclear which one the child inherits. Java lets a class extend only one class but implement any number of interfaces, which gives multiple inheritance of type. (If two interfaces supply the same
defaultmethod, the compiler makes the class override it and choose.)Overloading Overriding Same class: same name, different parameter lists Subclass: same name and same parameter list Chosen by the compiler (compile time) Chosen by the JVM from the actual object (run time) Return type may differ Return type the same, or a subtype From the top down: the constructor of the most general class finishes first (
Object, then each parent in turn) and the constructor of the class being created finishes last. This happens because each constructor callssuper(...)before running its own body.
Practice exercises
- Create Vehicle (brand, speed), subclasses Car and Bike, and override
describe()in each. - Create a hierarchy Employee with subclasses Manager and Developer. Each overrides
calculateSalary(). - Draw a class hierarchy for a school: Person, Student, Teacher, Principal.
- Write a class Smartphone that implements both Camera and Phone interfaces.
- Print messages in each constructor of a three-level hierarchy and predict the order before running.
Hint
The parent constructor messages print first, then the child's, going down the hierarchy.