×
☰ See All Chapters

Private Interface Methods

From Java 9 onwards, we can create private and private static methods in an interface. private methods should not include default and abstract modifiers.  Before Java 9, creating private methods inside an interface cause a compile time error.  private methods can be used by any other private methods and default methods inside interface. No static methods can access private or default methods. Static members can access only static members, but static members can be accessed by any member. private static methods can be used by any methods inside interface.

Members of interface in Java 9

  1. public static final variables: static and final specifiers are optional. Java compiler adds static final keyword to variables if not added. 

  2. public abstract methods: public and abstract specifiers are optional. Java compiler adds public and abstract keyword to interface methods if not added. 

  3. public default methods 

  4. public static methods 

  5. private methods. private methods should not include default and abstract modifiers. 

  6. private static methods. 

package com.java4coding;

interface TestIntefaceInJava9 {

        public static final int var = 10;

        public abstract void meth();

        public default void a() {

                b();

                c();

        }

        private void b() {

                c();

        }

        private void c() {

                System.out.println("c");

        }

        public static void d() {

                e();

                f();

        }

        private static void e() {

                f();

        }

        private static void f() {

                System.out.println("e");

        }

}

 

private-interface-methods-0
 

Members of interface in Java 8

  1. public static final variables: static and final specifiers are optional. Java compiler adds static final keyword to variables if not added. 

  2. public abstract methods: public and abstract specifiers are optional. Java compiler adds public and abstract keyword to interface methods if not added. 

  3. public default methods 

  4. public static methods 

package com.java4coding;

interface TestIntefaceInJava9 {

        public static final int var = 10;

        public abstract void meth();

        public default void a() {

        }

        public static void d() {

        }

}

Members of interface in Java 7

  1. public static final variables: static and final specifiers are optional. Java compiler adds static final keyword to variables if not added. 

  2. public abstract methods: public and abstract specifiers are optional. Java compiler adds public and abstract keyword to interface methods if not added. 

package com.java4coding;

interface TestIntefaceInJava7 {

        public static final int var = 10;

        public abstract void meth();

}

private-interface-methods-1
 
private-interface-methods-2
 

All Chapters
Author