Java 8 introduced default and static methods, the previous post gives a few examples of
Java 8 default and static methods. Java 9 builds on that foundation and adds support for private interface methods. In this post, we will see a simple example of how to use private methods to interfaces. In general,
- Like any private method, private interface methods are accessible from within the enclosing interface only.
- Private methods can be declared using the
private
keyword. - Any
private
method has to be implemented in the interface as it cannot implemented in a sub-interface or implementing classes.
The following example shows how to create a private method in the interface and a default method calling it.
package interfaces;
public interface InterfaceA {
default String hello(String str) {
return privateAddon("InterfaceA : hello " + str);
}
private String privateAddon(String str) {
return "Private Addon : " + str;
}
}
The following is a simple implementation class of this interface
package interfaces;
public class PrivateInterfaceMethods implements InterfaceA {
public static void main(String[] args) {
PrivateInterfaceMethods example = new PrivateInterfaceMethods();
System.out.println(example.hello("world"));
}
}
Excellent Article!!! I like the helpful information you provide in your article.
ReplyDelete