Java8 new feature Java8 新特徵之一接口default method

參考 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

  • Not override the default method and will inherit the default method.
  • Override the default method similar to other methods we override in subclass..
  • Redeclare default method as abstract, which force subclass to override it.
相關文章
相關標籤/搜索