I was reading Effective Java by Joshua Bloch.
In Item 17: \"Use interfaces only to define types\", I came across the explanation where it is not advised to use Inte
If in future, we wish to change the interface that some classes are implementing (e.g., addition of some new methods).
If we add abstract methods(additional methods), then the classes (implementing the interface) must implements the additional method creating dependency constraint and cost overhead to perform the same.
To overcome this, we can add default methods in the interface.
This will remove the dependency to implement the additional methods.
We do not need to modify the implementing class to incorporate changes. This is called as Binary Compatibility.
Please refer the example below:
The interface that we are going to use
//Interface
interface SampleInterface
{
// abstract method
public void abstractMethod(int side);
// default method
default void defaultMethod() {
System.out.println("Default Method Block");
}
// static method
static void staticMethod() {
System.out.println("Static Method Block");
}
}
//The Class that implements the above interface.
class SampleClass implements SampleInterface
{
/* implementation of abstractMethod abstract method, if not implemented
will throw compiler error. */
public void abstractMethod(int side)
{System.out.println(side*side);}
public static void main(String args[])
{
SampleClass sc = new SampleClass();
sc.abstractMethod(4);
// default method executed
sc.defaultMethod();
// Static method executed
SampleInterface.staticMethod();
}
}
Note: For more detailed information, please refer default methods