Self-check questions
Write your answers first, then open the answers to check them.
- What are the two types of polymorphism and how is each achieved?
- In
Shape s = new Circle(3); s.area();whicharea()runs and why? - 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.
Circle's
area()runs. The reference type isShape, but the object is aCircle, and for an overridden method Java uses the class of the actual object at run time (dynamic binding).Code written for the general type, such as a loop that calls
area()on everyShape, 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
- Create Employee, Manager, Developer with overridden
calculateSalary(). Store all in one array and print the total payroll.Hint
JavaEmployee[] 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 } - Create Payment with subclasses CardPayment, CashPayment, MobilePayment that override
pay(double). Write a methodprocess(Payment p, double amount). - Add a new subclass to exercise 1 without changing the existing loop. Explain why this works.