參考 https://dzone.com/articles/interface-default-methods-javahtml
參考 https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.htmljava
Java 8
introduces 「Default Method」 or (Defender methods) new feature, which allows developer to add new methods to the interfaces
without breaking the existing implementation of these interfaces
. It provides flexibility to allow interface
define implementation which will use as default in the situation where a concrete class
fails to provide an implementation for that method
.oracle
Let consider a small example to understand how it works:ide
public interface oldInterface {
public void existingMethod();
default public void newDefaultMethod() {
System.out.println("New default method"
" is added in interface");
}
}
The following class will compile successfully in Java JDK 8,?flex
public class oldInterfaceImpl implements oldInterface {
public void existingMethod() {
// existing implementation is here…
}
}
If you create an instance
of oldInterfaceImpl:?spa
oldInterfaceImpl obj = new oldInterfaceImpl ();
// print 「New default method add in interface」
obj.newDefaultMethod();
In summary, Default methods enable to add new functionality to existing interfaces without breaking older implementation of these interfaces.code
When we extend an interface that contains a default method, we can perform following,orm