Question
How can I invoke a default method from a parent interface in a subclassing interface implementation in Java?
interface Parent {
default void defaultMethod() {
System.out.println("This is a default method in Parent interface.");
}
}
interface Child extends Parent {
default void callParentDefaultMethod() {
// Invoking the default method from the parent interface
Parent.super.defaultMethod();
}
}
Answer
In Java, when you have a subclassing interface that extends a parent interface with a default method, you can call that default method using the 'super' keyword followed by the parent interface's name. This allows you to incorporate functionality defined in the parent interface without overriding it.
interface Parent {
default void defaultMethod() {
System.out.println("This is a default method in Parent interface.");
}
}
interface Child extends Parent {
default void callParentDefaultMethod() {
// Call the default method from the Parent interface
Parent.super.defaultMethod();
}
}
class Test implements Child {
public static void main(String[] args) {
Test test = new Test();
test.callParentDefaultMethod(); // This will call the Parent's default method
}
}
Causes
- Understanding of interface inheritance in Java.
- Knowledge of default methods introduced in Java 8.
Solutions
- Declare the parent interface with a default method.
- In the child interface, use the syntax 'Parent.super.defaultMethod()' to call the parent interface's default method.
Common Mistakes
Mistake: Forgetting to use 'Parent.super' when trying to call the default method from the parent interface.
Solution: Always use the syntax 'Parent.super.methodName()' to invoke the parent interface's default method.
Mistake: Overriding the default method in the child interface without invoking the parent interface's default method.
Solution: If you need to keep the parent logic, just call the default method using 'Parent.super.methodName()' in your overridden method.
Helpers
- Java interface inheritance
- Java default methods
- call default method from interface
- subclass interface Java
- interface default method usage