The default method is useful, when situation comes to introduce new method or functionality in the existing interface.
In the previous version of java, new method can not be pushed in the already delivered interface. Because It leads to rework on all the implementation classes. Default Method will have there own default implementation on the interface. So , it stop us from the re implementation.
Every one aware of that , Java does not support multiple inheritance directly. As developer we cooked this design with help of interface. So, multiple interface can be implemented in one class. Interface had stopped the presence of diamond problem.
Situation has changed now. You can have implementation in the interface using default method. So, if we have more than one interface implemented in a single class , what will happen?
You can prioritize the calling order of the interface. It could be more text based explanation, will see code here.
package com.ran;
interface Car{
default void engine(){ System.out.println("Car Engine implemenation");
}
}
interface Boat{
default void engine(){
System.out.println("Boat Engine implemenation");
}
}
public class JamesBondSuperCar implements Car,Boat {
public void engine() { Car.super.engine();
Boat.super.engine();
} public static void main(String[] args) {
JamesBondSuperCar bond=new JamesBondSuperCar();
bond.engine();
}
}
The above code is self explanatory for JamesBondSuperCar. It has mixed of the boad and car functionality to drive the special effect on screen. Ya.! It helped here too.
No comments:
Post a Comment