Java 9 Private methods in Interfaces

Filed Under: Java

Java 9 has been released and there has been a lot of changes. Today we will look into Java 9 private methods in interfaces change.

Java 9 Private Methods in Interfaces

Java 9 private methods in interfaces

There has been a lot of changes in interfaces in recent java releases. Few days back I wrote an extensive post on Java 9 features. We will look into following sections in this post.

  1. Java 7 Interface
  2. Java 8 Interface Changes
  3. Java 9 Interface Changes
  4. Rules to define private methods in an Interface?
  5. Why do we need private methods in an Interface?
  6. Interview Questions And Answers

In this post, I have provided pseudocode only to understand this new feature because everyone knows what is an interface in java and what is a private method in Java.

Java 7 Interface

In Java SE 7 or earlier versions, an interface can have only two kinds of things.

  1. Constant variables
  2. Abstract methods

We couldn’t provide method implementations in interfaces. If we want to provide the combination of abstract methods and non-abstract methods (methods with implementation), we had to go for abstract class only.


   public interface DBLogging{
      String MONGO_DB_NAME = "ABC_Mongo_Datastore";
      String NEO4J_DB_NAME = "ABC_Neo4J_Datastore";
      String CASSANDRA_DB_NAME = "ABC_Cassandra_Datastore";

      void logInfo(String message);
      void logWarn(String message);
      void logError(String message);
      void logFatal(String message);
   }

Here we have defined couple of constants and public abstract methods. What if I would like to provide some implementation to these methods here, say default implementation. Then we should go for abstract class in Java 7 or earlier versions.

Java 8 Interface Changes

Oracle Corporation has introduced some new features to interface in Java 8 Release. That is Default methods and Static methods feature.

Yes, we can write method implementations in Interface from Java 8 onwards. We need to use default keyword to define them as shown below.

In Java 8, an interface can have only four kinds of things:

  1. Constant variables
  2. Abstract methods
  3. Default methods
  4. Static methods

Default and Static methods were added in Java 8 interface changes.


   public interface DBLogging{
      String MONGO_DB_NAME = "ABC_Mongo_Datastore";
      String NEO4J_DB_NAME = "ABC_Neo4J_Datastore";
      String CASSANDRA_DB_NAME = "ABC_Cassandra_Datastore";

      // abstract method example
      void logInfo(String message);

      // default method example
      default void logWarn(String message){
         // Step 1: Connect to DataStore
         // Step 2: Log Warn Message
         // Step 3: Close the DataStore connection
      }
      default void logError(String message){
         // Step 1: Connect to DataStore
         // Step 2: Log Error Message
         // Step 3: Close the DataStore connection
      }
      default void logFatal(String message){
         // Step 1: Connect to DataStore
         // Step 2: Log Fatal Message
         // Step 3: Close the DataStore connection  
      }
      // static method example
      static boolean isNull(String str) {
	System.out.println("Interface Null Check");
	return str == null ? true : "".equals(str) ? true : false;
      }
      // Any other abstract, default, static methods
   }

Above example shows everything we can do in Java 8 interfaces, notice the extra set of default and static methods.

Did you notice the code redundancy in all the log methods? Every method is opening and closing a connection on it’s own. If we want code reuse, then we will have to move these common code to a public method, but then it will be accessible to all other classes.

What if we want to reuse the code but also don’t want to expose it to others? We will have to go for abstract class with a private method for the common code.

Java 9 Interface Changes

To provide a resolution to above scenarios, Oracle Corporation has introduced private methods in interfaces in java 9 release.

From Java 9 onwards, we can write private methods in interfaces using private access modifier as shown below (like other private methods).

In Java 9 and later versions, an interface can have six kinds of things:

  1. Constant variables
  2. Abstract methods
  3. Default methods
  4. Static methods
  5. Private methods
  6. Private Static methods

Private methods and private static methods are added in Java 9 interface changes.


public interface DBLogging {
	String MONGO_DB_NAME = "ABC_Mongo_Datastore";
	String NEO4J_DB_NAME = "ABC_Neo4J_Datastore";
	String CASSANDRA_DB_NAME = "ABC_Cassandra_Datastore";

	default void logInfo(String message) {
		log(message, "INFO");
	}

	default void logWarn(String message) {
		log(message, "WARN");
	}

	default void logError(String message) {
		log(message, "ERROR");
	}

	default void logFatal(String message) {
		log(message, "FATAL");
	}

	private void log(String message, String msgPrefix) {
		// Step 1: Connect to DataStore
		// Step 2: Log Message with Prefix and styles etc.
		// Step 3: Close the DataStore connection
	}
	// Any other abstract, static, default methods
}

Here we have moved redundant code into a common private method so that our API Clients can’t see them. Notice the below image from Eclipse Oxygen supporting Java 9.

java 9 interface private methods

Rules to define private methods in an Interface?

While writing private methods in an Interface, we should follow these rules:

  1. We should use private modifier to define these methods.
  2. No private and abstract modifiers together, it will give compiler error.
  3. It is not a new rule. We cannot use the combination of private and abstract modifiers, because both have different meanings.

    • The “private” method means fully implemented method because sub-classes cannot inherit and override this method.
    • The “abstract” method means no-implementation method. Here sub-classes should inherit and override this method.

    That’s why private methods should have full implementation.

  4. Private methods must contain body.
  5. No lesser accessibility than private modifier.
  6. In Java, as we know private is the least visible access modifier. So we cannot reduce it’s visibility from private to any other modifier.

These interface private methods are useful or accessible only within that interface only. We cannot access or inherit private methods from an interface to another interface or class.

Why do we need private methods in Interface?

Java 9 private methods in interfaces have following benefits.

  1. No need to write duplicate code, hence more code reusability.
  2. We got the choice to expose only our intended methods implementations to clients.

That’s all about Java 9 private methods in interfaces change.

Reference: JEP 213: Milling Project Coin

Comments

  1. Pitchireddy says:

    in Java8, it has static method in interface…this is not overriding in subclass..what is the use of static method in interface?

    1. Pramod says:

      Hii Reddy,
      Suppose you have so many classes which required common behaviour for all the classes which is implementing the common interface. so instead of duplicating code in all the classes, just write one static method in interafece and provide the behaviour. so all the classes can call the static method and get the benefits.

      1. MuraliKrishna says:

        for that we can write method in utility class and we can use for all classes, no need to write private method in interface.

  2. Chinna says:

    Very Good Post, thank you.

  3. Tejaswita Bhanushali says:

    In Java 9 they have allowed static private method in interface what is use of it as private methods are inaccessible from the subclass then. Anyway static method never take part in polymorphism????

    1. MuraliKrishna says:

      private static method is just to load when class loads with main(). both methods are same, static methods will loads when class loads and non static methods loads when we invoke that method

      1. Ramana says:

        What is the use of private method in interface we are not actually using in the implemented sub classes

  4. Antony Gabriel says:

    Is interface killing Abstract class?

  5. adiseshu says:

    import java.util.function.IntPredicate;
    import java.util.stream.IntStream;

    interface Calc
    {
    default int addNaturalNumbers(int… nums){
    int sum = 0;
    for(int i:nums)
    {
    sum = sum+i;
    }
    return sum;
    }
    default int addEvenNumbers(int… nums){
    int sum = 0;
    for(int i:nums)
    {
    sum = sum+i;
    }
    return sum;
    }
    default int addOddNumbers(int… nums){
    int sum = 0;
    for(int i:nums)
    {
    sum = sum+i;
    }
    return sum;
    }
    }
    class MyCalc implements Calc{}
    class Test{
    public static void main(String[] args){
    MyCalc myCalc = new MyCalc();
    int sumOfNaturalNumbers = myCalc.addNaturalNumbers(1,2,3,4,5);
    System.out.println(sumOfNaturalNumbers);

    int sumOfEvens = myCalc.addEvenNumbers(2,4,6);
    System.out.println(sumOfEvens);

    int sumOfOdds = myCalc.addOddNumbers(1,3,5);
    System.out.println(sumOfOdds);
    }
    }

    Problem in the above program:
    In the above program the add functionality is redundant in each method.

    Solution:
    1. If we want code reuse, then we have to move this common code to pubic method. But public methods will be accessible to all other classes.

    2. If we want to reuse the code but outside person not allowed to access code then we have to go for abstract class with a private method with common code.

    3. Java 9 provides a solution to above problem with private methods in interfaces.

    import java.util.function.IntPredicate;
    import java.util.stream.IntStream;

    interface Calc
    {
    default int addNaturalNumbers(int… nums){
    return add(nums);
    }
    default int addEvenNumbers(int… nums){
    return add(nums);
    }
    default int addOddNumbers(int… nums){
    return add(nums);
    }
    private int add(int… nums){
    int sum = 0;
    for(int i:nums)
    {
    sum = sum+i;
    }
    return sum;
    }
    }
    class MyCalc implements Calc{}
    class Test{
    public static void main(String[] args){
    MyCalc myCalc = new MyCalc();
    int sumOfNaturalNumbers = myCalc.addNaturalNumbers(1,2,3,4,5);
    System.out.println(sumOfNaturalNumbers);

    int sumOfEvens = myCalc.addEvenNumbers(2,4,6);
    System.out.println(sumOfEvens);

    int sumOfOdds = myCalc.addOddNumbers(1,3,5);
    System.out.println(sumOfOdds);
    }
    }

  6. Harish Kumar says:

    Hello Ram

    Nice brief about this feature. Is this not like mixing too many things in same pot? Is there any intent to take away abstract classes from Java.

    Also you have written same for all versions of Java mentioned in tutorial Am I missing anything here?:
    In Java SE 9 and later versions, an interface can have only two kinds of things;
    In Java SE 8 and later versions, an interface can have only two kinds of things;
    In Java SE 7 and later versions, an interface can have only two kinds of things

    1. Pankaj says:

      I don’t think Abstract Classes can be removed, it will break too many things.

      Thanks for pointing out the error in writing, I have corrected it and made it clear.

  7. Smruti Ranjan says:

    Thank you sir for these brief introduction.

  8. Vinayak A says:

    Hi Sir,

    Thanks for sharing such a nice post.

  9. Anand says:

    Awesome post! After a long time, I have seen such a nicely created blog on Java. As true fan of Java, I really admire your efforts! Keep on producing such good stuff.

  10. Ramesh says:

    Wow Awesome perfectly explained versions about interface in SE 7 8 9

  11. ramya says:

    As private methods cannot be over ride in sub class , how to access a private method of interface

    1. Rambabu says:

      Hi

      Good question. Those private methods are useful or intended only for that interface only. We cannot access them outside that interface.
      Updated the post with this point.

      Ram

      1. Kumar says:

        Can we make use of static methods here? Why there is a need of private method?

        1. Joseph Grigg says:

          In Java 8 static methods were introduced into Interfaces but were public. I’m sure in Java 9 the introduction of static private methods is so that the static public methods are able to use helper methods that are not intended to become part of the public API. Static methods cannot call non-Static methods without an instance of the object that method is declared on, therefore, static private methods are added.

  12. Sagar Mangelkar says:

    Small correction :
    MONGO_DB_NAME, NEO4J_DB_NAME, CASSANDRA_DB_NAME should be `String` .
    Nice post.

    1. Rambabu says:

      Thanks, updated that type error.

      Ram

  13. Naresh Makhija says:

    Very good post but i want to know more things about java please mail me as you update about java 9

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages