Java 9 Private Interface Methods:
- From Java 9 onwards, we can create private non-static/static methods inside an interface.
- The interface allows us to define private methods that help to share common code between non-abstract/default methods.
- Prior to Java 9, When you create private methods inside an interface then you will get a compile-time error.
Private methods in interfaces have four rules :
- Private methods in the interface cannot be abstract.
- The private method can be used only inside the interface.
- We can use the private static method inside other static and non-static/ interface methods.
- private non-static methods cannot be used inside private or public static methods.
Let’s try to understand the above points using the below example.
Welcome.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package com.kkjavatutorials.org; /** * @author KK JavaTutorials *private methods in interface in java 8 */ public interface Welcome { public abstract void sayHi(); public default void greet() { System.out.println("Welcome to Java 9"); wecome1(); wecome2(); } public static void test() { System.out.println("Test.."); //wecome1(); //Can't access non-static private method wecome2();// Can access static private method } /** * private non static method in interface */ private void wecome1() { System.out.println("Welcome again to Java 9.."); } /** * private static method in interface */ private static void wecome2() { System.out.println("private static method.."); //wecome1();//Can't access non-static method private method } } |
WelcomeImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.kkjavatutorials.cleint; import com.kkjavatutorials.org.Welcome; public class WelcomeImpl implements Welcome { @Override public void sayHi() { System.out.println("Hi"); } public static void main(String[] args) { Welcome welcome = new WelcomeImpl(); welcome.sayHi(); welcome.greet(); Welcome.test(); } } |
If you run WelcomeImpl.java as Java Application then it will give the below output:
1 2 3 4 5 6 |
Hi Welcome to Java 9 Welcome again to Java 9.. private static method.. Test.. private static method.. |
That’s all about Java 9 private Interface Methods
You May Also Like:
Java 9 Jshell Tutorial
Java 9 Try with Resource Enhancement
Java 9 @SafeVarargs Annotation
Java 9 Collection Factory Methods
Java 9 Stream API improvements
If you have any feedback or suggestion please feel free to drop in below comment box.