Java8 new feature One of the new features of Java8 is the interface default method

Refer to  https://dzone.com/articles/interface-default-methods-java

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324933944&siteId=291194637
Recommended