Take the following interface:
public interface Cooking {
public void fry();
public void boil();
public void chop();
}
To add new functionality, simply adding a new method to Cooking
called microwave()
will cause problems. Any class that previously implemented Cooking
will now have to be updated in order to function again.
To avoid this, give microwave()
a default implementation:
public interface Cooking {
public void fry();
public void boil();
public void chop();
default void microwave() {
//some code implementing microwave
}
}
As microwave()
already has a default
implementation defined in the Cooking
interface definition, classes that implement it now don’t need to implement microwave()
in order to work.
This allows us to add functionality without breaking old code.
Note: This has been possible since Java 8.