OOP: Polymorphism & Interfaces

☕ Java Lesson 13 Advanced

Polymorphism allows objects to take on many forms. It enables a parent type reference to hold a child subclass object, executing runtime dynamic method dispatch.

1 Abstract Classes vs Interfaces

Java supports two abstraction frameworks:

  • Abstract Class: A class declared `abstract` that cannot be instantiated. Can contain constructor fields, instance states, and fully defined methods alongside abstract method signatures.
  • Interface: A contract definition. Interfaces contain no instance fields (only static final constants) and by default specify abstract signatures. Classes implement interfaces using the `implements` keyword. A class can implement multiple interfaces.
2 Polymorphism and Dynamic Method Dispatch

When you reference a child object using a parent type, Java decides which method implementation to run at runtime based on the actual object type, not the reference type. Let's observe this pattern:

Java — Abstraction and Interfaces ▶ Run Code
interface Drivable {
    void drive(); // Interface abstract method
}

class Car implements Drivable {
    @Override
    public void drive() {
        System.out.println("Car is driving on roads.");
    }
}

class Boat implements Drivable {
    @Override
    public void drive() {
        System.out.println("Boat is cruising on water.");
    }
}

public class Main {
    public static void main(String[] args) {
        // Polymorphism: Reference type is the interface, object is concrete child
        Drivable v1 = new Car();
        Drivable v2 = new Boat();

        // Dynamic Method Dispatch determines execution at runtime
        v1.drive();
        v2.drive();
    }
}
3 Code Challenge
Challenge: Write an interface called `PaymentMethod` with an abstract method `pay(double amount)`. Create two classes implementing this interface: `CreditCard` and `PayPal`. Write a main simulation demonstrating polymorphic method dispatch by storing them inside an array of type `PaymentMethod[]` and looping through to invoke payments.