Unit 3 · OOP Concepts

3.6.4Self-check and practice

Self-check questions

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

  1. What are the two types of polymorphism and how is each achieved?
  2. In Shape s = new Circle(3); s.area(); which area() runs and why?
  3. Why does polymorphism make programs easier to extend?
Show answers
    • Compile-time polymorphism (static binding) is achieved by overloading: the compiler picks the method from the argument types.
    • Run-time polymorphism (dynamic binding) is achieved by overriding: the JVM picks the version that belongs to the actual object.
  1. Circle's area() runs. The reference type is Shape, but the object is a Circle, and for an overridden method Java uses the class of the actual object at run time (dynamic binding).

  2. Code written for the general type, such as a loop that calls area() on every Shape, works for any subclass, including ones added later. To add a new kind of shape you write one new class with its own override; the existing code does not change.

Practice exercises

  1. Create Employee, Manager, Developer with overridden calculateSalary(). Store all in one array and print the total payroll.
    Hint
    Java
    Employee[] staff = { new Manager("Ama", 150000), new Developer("Kasun", 120000) };
    double total = 0;
    for (Employee e : staff) {
        total += e.calculateSalary();   // the right version runs for each object
    }
  2. Create Payment with subclasses CardPayment, CashPayment, MobilePayment that override pay(double). Write a method process(Payment p, double amount).
  3. Add a new subclass to exercise 1 without changing the existing loop. Explain why this works.