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"));
}
}
Wow! this is Amazing! Do you know your hidden name meaning ? Click here to find your hidden name meaning
ReplyDeleteIt's really good article..Thanks for sharing.
ReplyDeleteDevOps Training
DevOps Online Training
Impressive!Thanks for the post
ReplyDeleteBest Travel Agency in Madurai | Travels in Madurai
Madurai Travels | Best Travels in Madurai
Tours and Travels in Madurai | Best Tour Operators in Madurai
Excellent Article!!! I like the helpful information you provide in your article.
ReplyDelete