java 9 - topjavatutorial.com

Java 9 : Private Interface Methods

What are Private Methods in an Interface ?

Java 8 introduced the concept of default methods in Interface. It basically lets us provide a default implementation for a method in an interface.

For example :

public interface MyInterface {

  // default method
  default void hello(String name) {
    System.out.println("Hello " + name);
  }
}

So, unless the method hello() is overridden in the child class, we can still call it with a name (e.g. John) and it would print “Hello John” in console.

However, an interface can multiple such default methods.

So, there is a possibility of code duplication among them.

private interface methods can be used in such scenarios.
 
Here is an example of using private interface methods :

package com.topjavatutorial;

public interface MyInterface {

  // default method
  default void hello(String name) {
    System.out.println("Hello " + name);
    verifyName(name);
  }
  
  private static void verifyName(String name){
    if(name == null || name.length() < 0)
      throw new IllegalArgumentException();
  }
}

 

What is the advantage of using Private methods in Interface ?

Private methods can reduce code duplication among default and static methods in an Interface.

For example, if two or more default methods needed to share some code, a private interface method could be created for the same and can be called from each of the default methods.

 

Static vs Instance Private Interface Method

A private interface method can be a static or instance method.

A static private interface method belongs to the interface whereas an private interface method without the static keyword can be called by an interface instance within the interface code.

public interface MyInterface {

  // belongs to Instance of the interface
  private void instancePrivateMethodVerifyName(String name){
    //code
  }

  // belongs to the Interface
  private static void staticPrivateMethodVerifyName(String name) {
    // code
  }

  // default method
  default void hello(String name) {
    staticPrivateMethodVerifyName(name);

    MyInterface intf = new MyInterface() {
    };
    intf.instancePrivateMethodVerifyName(name);
  }
}

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags