Inheriting Default Methods
What you'll learn: How classes automatically get default method implementations when they implement an interface.
When a class implements an interface that contains default methods, the class automatically inherits those default method implementations. You don't need to write any code—the default method just works as if it were defined in the class itself.
The Core Idea
Think of default methods like inheritance from a superclass. When you implement an interface with a default method, your class receives that method "for free." You can call it on instances of your class without writing any implementation.
This is the main benefit of default methods: they let you add behavior to interfaces without breaking existing classes that implement them.
How Inheritance Works
When you implement an interface with default methods:
- The class inherits all default methods automatically
- You can call them directly on class instances
- The class doesn't need to override them (but it can if needed)
- Multiple objects of the class all share the same default behavior
interface Greetable {
default void greet() {
System.out.println("Hello!");
}
}
class Person implements Greetable {
// No need to implement greet() - it's inherited!
}
class Main {
public static void main(String[] args) {
Person p = new Person();
p.greet(); // Prints: Hello!
// The greet() method is inherited from Greetable
}
}
The Person class doesn't define greet(), yet you can call it. It was inherited from the Greetable interface's default implementation.
Key Takeaway: Classes automatically inherit default methods from their interfaces, gaining that functionality without any additional code—just like inheriting concrete methods from a superclass.