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.
Why do we need private methods in an interface in Java 9?
An interface supports default methods since Java 8 version. Sometimes these default methods may contain a code that can be common in multiple methods. In those situations, we can write another default method and make code reusability. When the common code is confidential then it's not advisable to keep them in default methods because all the classes that implement that interface can access all default methods.
An interface can have private methods since Java 9 version. These methods are visible only inside the class/interface, so it's recommended to use private methods for confidential code. That's the reason behind the addition of private methods in interfaces.
Let us consider 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 PrivateDemo implements Printable {
public static void main(String[] args){
Printable p = new PrivateDemo();
p.print3D();
}
}
Output:
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.