In this section, we will learn what the interface private method is and how to use it in Java.
Note: in this section, we’re assuming you’re already familiar with interface and default methods.
What is Private Method in Java Interface?
Sometimes we want to set the body of a method inside the interface, but we want to use that method just inside the interface itself!
This is where private methods come in.
Private methods in an interface are just like default methods (they have a body in the interface) with the exception that they are not accessible via external objects and any classes that implement the interface.
How to Define Private Method in Java Interface?
In order to create a private method in an Interface, make sure you’ve set the access-specifier of that method to `private` and create a body of it.
Example: using private Method in Java Interface
public interface FirstInterface { private void method1(){ System.out.println("This message is coming from a private method"); } default void method2(){ method1(); } }
Here the `method1` is private and so only accessible in the interface itself.
Example: invoking private method of Java interface
Now let’s create a class and implement the interface:
public class SClass implements FirstInterface { } public class Simple { public static void main(String[] args) { SClass sClass = new SClass(); sClass.method2(); } }
Output:
This message is coming from a private method