Interfaces in Java are usually a mechanism for allowing a number of classes to share a number of methods and constants. It is also one of the best mechanisms for achieving Polymorphism in Java.
So if you are the type that is very familiar with Interfaces before the arrival of Java 8, it would make a great deal of sense to also discover some of the cool stuff Interfaces can now do in Java 8. Let’s dive in.
Interfaces before Java 8 used to contain only abstract methods and constants and any class that implements an Interface must implement all its methods or be declared an abstract. Well, this is before Java 8. With Java 8, this has been upgraded.
Interfaces can now contain methods with implementations. Yes, for real. Such methods that have an implementation right from the interface are called default methods. These allow for a default implementation of a method by all classes that implement an interface and provide the opportunity for the implementing classes to override the method if they so wish.
public interface Bank{
default String getBankName(){
return “Azibit Bank”;
}
}
Note the syntax for the default method. It must be preceded by the default keyword.
With this introduction, the major concern on the mind of every Java Developer is how does this new concept manage Multiple Inheritance from different interfaces or if a class and an interface have the same method. Well, such fear was anticipated and so the following rules apply when more than one interface have the same method and a class implements the two of them.
- A class implementation of a method takes precedence over a default method. So, if the class already has the same method as an Interface, then the default method from the implemented Interface does not take effect.
- However, if two interfaces implement the same default method, then there is a conflict.
- In cases where one interface inherits another interface and both of them implement a default method, an implementing class would use the default method of the child interface.
- Also, an explicit call to an interface default method can be made from inside an implementing class using super. For example Interface.super.defaultMethod().
Also, Java 8 introduces static methods in Interfaces. So, interfaces can now create static methods and reference these static methods from anywhere simply by calling the Interface name followed by the method name. For example: InterfaceName.staticMethodName().
To create a static method, you would need to add the static keyword when creating the method.
public interface Test{
static String getStaticNumber(){
return 1;
}
}
Reference: Java The Complete Reference, By Herbert Schildt
Join the Red Hat Developer Program (it’s free) and get access to related cheat sheets, books, and product downloads.
Click here to download OpenJDK, a free and open source implementation of the Java Platform.
Last updated: November 9, 2017