Interface Private Methods
The interface is a concept in Java that is used to achieve abstraction. It contains fields and methods, initially interface allowed only abstract methods but version after version it changed and allowed other types of methods as well. Let's see a brief idea of interface improvements.
In earlier Java versions, interfaces can only contain public abstract methods and these methods must be implemented by implemented classes.
In Java 8, apart from public abstract methods, an interface can have static and default methods.
In Java 9, we can create private methods inside an interface. The interface allows us to declare private methods that help to share common code between non-abstract methods.
Before Java 9, creating private methods inside an interface cause a compile-time error.
Since java 9, you will be able to add private methods and private static methods in interfaces. Let's understand by using some examples.
Time for an Example:
In this example, we created a private method print() inside an interface. since it is private so we cannot call it outside the interface that's why we call it from a default method.
interface Printable{
private void print() {
System.out.println("print...");
}
default void print3D() {
// Calling private method
print();
}
}
public class Main implements Printable {
public static void main(String[] args){
Printable p = new Main();
p.print3D();
}
}
print...
Example: Java older version(Before Java9)
If we execute this code by using Java older compiler like java 8 then compiler report an error.
interface Printable{
private void print() {
System.out.println("print...");
}
default void print3D() {
// Calling private method
print();
}
}
public class Main implements Printable {
public static void main(String[] args){
Printable p = new Main();
p.print3D();
}
}
Main.java:2: error: modifier private not allowed here
Example: Private Static Method
Like a private method, Java 9 allows creating private static methods inside an interface. See, the following example.
interface Printable{
private void print() {
System.out.println("print...");
}
private static void print2D() {
System.out.println("print 2D...");
}
default void print3D() {
// Calling private methods
print();
print2D();
}
}
public class Main implements Printable {
public static void main(String[] args){
Printable p = new Main();
p.print3D();
}
}
print...
print 2D...