Tuesday, October 03, 2017

Java 9 : Private interface methods

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,
  1. Like any private method, private interface methods are accessible from within the enclosing interface only.
  2. Private methods can be declared using the private keyword.
  3. 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"));
 }

}

5 comments:

  1. Excellent Article!!! I like the helpful information you provide in your article.

    ReplyDelete
  2. I think this is one of the most important pieces of information for me

    ReplyDelete
  3. Well done article. I'll make sure to use it wisely. Thank you for sharing

    ReplyDelete
  4. Hey, that's a clever way of thinking about it. fuckin amazing article

    ReplyDelete
  5. Fabulous stuff there you are! plss write more like this, you're awesome

    ReplyDelete

Popular Posts