Interfaces as Types: Polymorphic References
What You'll Learn
You'll learn how interface names can be used as reference variable types to hold any instance of a class that implements that interface, unlocking powerful polymorphism.
The Core Idea
Just like you can declare a variable with a superclass type and assign subclass instances to it, you can declare a variable with an interface type and assign any implementing class instance to it. This is one of the most powerful features of interfaces.
When you declare a reference variable using an interface type, that variable can point to any object whose class implements that interface. The variable doesn't care about the specific class—only that the object honors the contract defined by the interface.
Plain-English Analogy
Think of a power outlet interface: any device (laptop, phone, lamp) that implements the "plug-in-able" interface can be referenced as "a thing that plugs in." You don't need to know if it's specifically a laptop or lamp—you just know it can be plugged in and powered.
How It Works
interface Playable {
void play();
}
class Guitar implements Playable {
public void play() {
System.out.println("Strumming guitar");
}
}
class Piano implements Playable {
public void play() {
System.out.println("Playing piano");
}
}
// Interface as reference type:
Playable instrument1 = new Guitar(); // Valid!
Playable instrument2 = new Piano(); // Also valid!
instrument1.play(); // "Strumming guitar"
instrument2.play(); // "Playing piano"
The reference type is Playable, but the actual objects are Guitar and Piano. Dynamic dispatch ensures the correct play() method runs.
Key Takeaway: Interface types can serve as polymorphic reference variables, allowing you to write flexible code that works with any implementing class without knowing the specific type at compile time.