Polymorphism Through Interfaces in Java
Just like a superclass-typed variable can refer to any of its subclasses' objects, a variable typed as an interface can refer to an object of any class that implements it — Flyable f = new Bird(); is legal, and calling f.fly() runs whichever implementation the object's actual class provides. This lets code be written entirely against an interface type, accepting any implementing class without ever needing to know or check which specific one it actually received — the same polymorphic benefit inheritance offers, but without requiring the implementing classes to share any common superclass at all.
This is especially powerful for otherwise-unrelated classes. A Bird and an Airplane share no meaningful inheritance relationship, but both can implement Flyable and be treated identically by any code written against that interface type.
An interface-typed reference to an implementing object
Flyable f = new Bird(); is legal, since Bird implements Flyable.
Which implementation actually runs
Calling f.fly() runs whichever version the object's real, actual class provides.
Code written against the interface stays generic
It never needs to check which specific implementing class it actually received.
Works across unrelated classes
A Bird and an Airplane need no inheritance relationship at all to both be treated as Flyable.
Collections of an interface type
A list declared as List<Flyable> can hold objects of any class that implements Flyable, mixed freely.
interface Flyable { void fly();} class Bird implements Flyable { public void fly() { System.out.println("Bird flapping wings"); }} class Airplane implements Flyable { public void fly() { System.out.println("Airplane using jet engines"); }} public class InterfacePolyDemo { public static void main(String[] args) { Flyable[] flyers = { new Bird(), new Airplane() }; for (Flyable f : flyers) { f.fly(); } }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.