Java · Module 6 · Lesson 32 min read

Polymorphism & Interfaces

Polymorphism = "many forms"

  1. Compile-time polymorphism → method overloading (Unit 5).
  2. Runtime polymorphism → method overriding.

Overriding

A subclass gives its own version of a parent method with the same signature.

Java
class Animal { String sound() { return "..."; } }
class Dog extends Animal {
    @Override String sound() { return "Woof"; }
}

Animal a = new Dog();     // parent reference, child object
a.sound();                // "Woof" — chosen at runtime

@Override asks the compiler to check you really are overriding. Always use it!

Abstract classes

An abstract class is an incomplete blueprint:

  • It can't be created with new.
  • It can have abstract methods (no body) that subclasses must implement.
  • It can also have normal methods, fields and constructors.
Java
abstract class Shape {
    abstract double area();
    void describe() { System.out.println("Area: " + area()); }
}

Interfaces

An interface is a contract: "anything that implements me can do these things".

Java
interface Playable {
    void play();
    default void pause() { System.out.println("Paused"); }  // Java 8+
}
class Song implements Playable {
    public void play() { System.out.println("♪"); }
}
  • A class can implement many interfaces: class Phone implements Camera, MusicPlayer.
  • Interfaces can have default and static methods (Java 8+) and private helpers (Java 9+).
  • Fields in interfaces are automatically public static final constants.

Abstract class or interface?

Use an abstract class when…Use an interface when…
Subclasses share code and stateUnrelated classes share a capability
There's a clear IS-A familyYou need multiple "types" on one class

Sealed classes (Java 17+)

sealed interface Shape permits Circle, Square { } limits which classes may implement it, so the compiler knows every possible case.

Example

Java
interface Shape {
    double area();
    default String describe() {
        return getClass().getSimpleName() + " with area " + String.format("%.1f", area());
    }
}

record Circle(double r) implements Shape {
    public double area() { return Math.PI * r * r; }
}

record Rectangle(double w, double h) implements Shape {
    public double area() { return w * h; }
}

public class Gallery {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1), new Rectangle(2, 3) };
        for (Shape s : shapes) {
            System.out.println(s.describe());  // each shape uses its own area()
        }
        // Circle with area 3.1
        // Rectangle with area 6.0
    }
}