Calling a default method from an interface inside a class that implements it is straightforward, and it becomes especially important when there’s a conflict between multiple default methods.
✅ How to Call a Default Method in a Class
If you’re in a class that implements the interface, and you want to explicitly call the default implementation, use this syntax:
InterfaceName.super.methodName();
🧠 Example:
interface Greetable {
default void greet() {
System.out.println("Hello from Greetable");
}
}
class Person implements Greetable {
@Override
public void greet() {
System.out.print("Person says: ");
Greetable.super.greet(); // Calls the default method
}
}
new Person().greet(); // Output: Person says: Hello from Greetable
⚔️ Why Use InterfaceName.super.method()
?
- To reuse default implementation
- To resolve conflicts when your class implements multiple interfaces with the same method
⚠️ Important Notes
- You can only call it from within an instance method of the implementing class — not from a static context.
- You must use the interface name — not just
super.method()
.
💡 Diamond Problem Example
interface A {
default void hello() { System.out.println("Hello from A"); }
}
interface B {
default void hello() { System.out.println("Hello from B"); }
}
class C implements A, B {
@Override
public void hello() {
// Must resolve the conflict manually
A.super.hello(); // or B.super.hello()
}
}
✅ Summary
You Want To… | You Do This |
---|---|
Call a default method in implementing class | InterfaceName.super.methodName(); |
Resolve conflict between multiple interfaces | Explicitly choose which one to call |