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

参考 https://dzone.com/articles/interface-default-methods-java

参考 https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

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.

Let consider a small example to understand how it works:

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,?

public class oldInterfaceImpl implements oldInterface {
public void existingMethod() {
// existing implementation is here…
}
}

If you create an instance of oldInterfaceImpl:?

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.

When we extend an interface that contains a default method, we can perform following,

  • 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.

猜你喜欢

转载自my.oschina.net/u/2308739/blog/1801760