Suppose you are working on a very very big java project.
Congratulations!!!
Problem Scenario
Suddenly your senior comes to your desk and says- "Hey X, we need to add a new method to XYX interface".
Inside your brain
Holy Crap!
Impossible, I can't do this.
It will break all existing code blocks.
No, it is not possible.
Why it is not possible?
According to oracle documents, a java interface is a group of related methods with empty bodies. Like-
interface Bicycle {
// wheel revolutions per minute
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
Suppose, already 100 classes implement Bicycle interface. So, if you want to add a new method in the Bicycle interface-
- You need to modify 100 classes. Complete the method's body in each and every classes, who implements bicycle interface.
Can it be a feasible solution?
No, never.
Solution
Java 8 introduced completely a new concept to overcome this crucial situation.
It is default method
Using default keyword, you can add a complete method in a java interface(magic), this will help you maintain existing legacy code, untouched.
With a new default method in Bicycle interface-
interface Bicycle {
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
//method with body in an interface
default void saveTheWord(){
System.out.println("Haha! it is a magic");
}
}
Now, you don't need to modify 100 existing classes(if you wish you can). However, after this point, newly implemented classes can use/override this method if they want.
Extending Interfaces That Contain Default Methods
When you extend an interface that contains a default method, you can do the following:
- Not mention the default method at all, which lets your extended interface inherit the default method.
- Redeclare the default method, which makes it abstract.
- Redefine the default method, which overrides it.
Top comments (0)