Java 8 Interface With Default Method#
Definition#
-
Before the Java 8 an interface has one or multiple implementations, if one or more methods are added to the interface, all the implementations will be forced to implement them too. Otherwise, the design will just break down.
-
Default interface methods are an efficient way to deal with this issue. They allow us to add new methods to an interface that are automatically available in the implementations. Therefore, we don’t need to modify the implementing classes.
-
In this way, backward compatibility is neatly preserved without having to refactor the implementers.
- Default methods help us expand interface without broken classes that implemented.
- Default methods will help us in avoiding utility classes.
- Default methods will help us in removing base implementation classes, we can provide default implementation and the implementation classes can choose which one to override.
-
If there are any class that inherit a same default method, the this default method will not be valid. The same thing is that a default method can not override a method from java.lang.object because Object is the base class of all classes in java. So, If we have methods in Object class which are defined as default methods in interface, the methods in Object class will be always used. This is the reason why we do not have any default methods can override methods of Object class.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Multiple Interface Inheritance Rules#
- As we know that, Java does not allow multi inheritances with class because the compiler does not know choose which method of super class to use. So, this happens the same for default method because if you implement a class from 2 interface Ex: FirstInterface and SecondInterface, the compiler does not know choosing which one to execute. Multi inheritances is a normal thing in java, we usually see this issue in java core classes, also most of enterprise and framework application. To ensure this issue can not with interface, class has to implement common methods default from 2 interface. So, as in the example below, class have to implement log() method for compiler can not throw exception.
FirstInterface.java | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
SecondInterface.java | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
MyImpl.java | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
- As we can see that in the
MyImpl
when we implement 2 interfaces, we must implement the default methodlog
if not we will see the compile error. In theMyImpl
we can also use the default methods fromFirstInterface
andSecondInterface
also.
JavaDefaultMethodInterfaceMain.java | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
- Finally, we have the result as below.
1 2 3 4 5 6 7 8 9 10 11 |
|