Unit 3 · OOP Concepts

3.5.6Self-check and practice

Self-check questions

Write your answers first, then open the answers to check them.

  1. What does "is-a" mean? Give two examples.
  2. Why does Java not allow a class to extend two classes? How is multiple inheritance achieved?
  3. Difference between overloading and overriding (three points).
  4. In what order do constructors run in a hierarchy?
Show answers
  1. "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.

  2. 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 default method, the compiler makes the class override it and choose.)

  3. OverloadingOverriding
    Same class: same name, different parameter listsSubclass: 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 differReturn type the same, or a subtype
  4. 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 calls super(...) before running its own body.

Practice exercises

  1. Create Vehicle (brand, speed), subclasses Car and Bike, and override describe() in each.
  2. Create a hierarchy Employee with subclasses Manager and Developer. Each overrides calculateSalary().
  3. Draw a class hierarchy for a school: Person, Student, Teacher, Principal.
  4. Write a class Smartphone that implements both Camera and Phone interfaces.
  5. 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.