Back in the day, it was hard to add functionalities to inheritance without breaking the whole program., But now you can! How? You have to use default methods.
Whenever there is a need for a new method in inheritance, it can be done without implementing the method in every single class implementing the interface.
What are Multiple Default Methods?
Let’s consider a scenario. Let’s assume both A and B are interfaces containing a default method hugeCastle() and a class implements both interfaces. Which interface method would it implement? Oh, you don’t know. Here are a set of rules to help you.
- If the implementing class has its own implementation for the default method, then that implementation will take priority over the others.
- If the class doesn’t contain its own implementation, then an error will be thrown: “Duplicate default methods named displayGreeting inherited from the interfaces.”
- In case when an interface extends another interface and both have the same default method, the inheriting interface default method will take precedence. Thus, if interface B extends interface A then the default method of interface B will take precedence.If the implementing class has its own implementation for the default method, then that implementation will take priority over the others.
- Super Keyword: Use a super keyword like so, interface.super.method() to implement the needed method from a specific interface.
Example
interface Dad{
default void throwTrash(){
String where = "I don't care, I am drunk";
System.out.println("I am going to throw the trash in the.... " + where);
}
}
interface Mom{
default void throwTrash(){
String where = "in your Dad's man cave";
System.out.println("I am going to throw the trash in the.... " + where);
}
}
class DefaultMethod implements Mom, Dad{
@Override
public void throwTrash(){
//Dad.super.throwTrash();
//Mom.super.throwTrash(); //Implements mom's method of throwing away trash
//String where = "in the trash can";
//System.out.println("I am going to throw the trash in the.... " + where); //Implements the child's way of throwing the trash
}
public static void main(String[] args) {
DefaultMethod dm = new DefaultMethod();
dm.throwTrash();
}
}
Layman’s Terms
When both your parent ask you throw out garbage but both of them specified different locations to dispose of the trash, what would you do? That’s how java feels. You can either throw wherever you want or use a super keyword and listen to one of them specifically. And Lastly, if it was your grandpa and your dad telling you to throw the trash out, you got the listen to your grandpa because he’s the man and top of the hierarchy.
References
https://www.programcreek.com/2014/12/default-methods-in-java-8-and-multiple-inheritance/
https://netjs.blogspot.com/2015/05/interface-default-methods-in-java-8.html