Introduction
Java 8 comes with use of default method in an interface. Multiple Interfaces can have the same default method.
Refer The Video For More Detail
Uses of Default Method
We can create a method with default keyword and the method will be referred from the interface.
In case if two interface have same default method then at the time of compilation only the editor will ask for the implementation of default method.
public interface DefaultInterface{
//Custom Codepublic default void getDefault() {
}
} |
In case if two interface have same default method then at the time of compilation only the editor will ask for the implementation of default method.
public interface DefaultInterface1 {
System.out.println("Default Interface1"); public default void getDefault() {
}
}
public interface DefaultInterface2 {
System.out.println("Default Interface2"); public default void getDefault() {
}
} |
When a class implements the above two interface then the user needs to override the default method of either of the interface. This will remove the diamond problem which occurs in multiple inheritance.
public class ImplementInterfaceWithDefaultMethod
implements DefaultInterface1,DefaultInterface2{ @Override public void getDefault() { DefaultInterface1.super.getDefault();
}
}
|
Conclusion
The default method can be created inside the interface since Java 8. It can be used by calling the Interface with its default method using super keyword.
No comments:
Post a Comment