Polymorphism & Interfaces
Polymorphism = "many forms"
- Compile-time polymorphism → method overloading (Unit 5).
- Runtime polymorphism → method overriding.
Overriding
A subclass gives its own version of a parent method with the same signature.
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
abstractmethods (no body) that subclasses must implement. - It can also have normal methods, fields and constructors.
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".
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
defaultandstaticmethods (Java 8+) andprivatehelpers (Java 9+). - Fields in interfaces are automatically
public static finalconstants.
Abstract class or interface?
| Use an abstract class when… | Use an interface when… |
|---|---|
| Subclasses share code and state | Unrelated classes share a capability |
| There's a clear IS-A family | You 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
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
}
}