Có, từ Java 9 trở đi, bạn có thể sử dụng phương thức private trong interface.
Trước Java 8, interface chỉ chứa hằng số và phương thức trừu tượng. Java 8 thêm default và static method. Java 9 cho phép private method (cả instance và static) để chia sẻ code giữa các phương thức default/static trong interface, tránh trùng lặp code.
Ví dụ minh họa
interface MyInterface {
public abstract void demo();
public default void defaultMethod() {
privateMethod();
staticPrivateMethod();
System.out.println("This is a default method of the interface");
}
public static void staticMethod() {
staticPrivateMethod();
System.out.println("This is a static method of the interface");
}
private void privateMethod(){
System.out.println("This is a private method of the interface");
}
private static void staticPrivateMethod(){
System.out.println("This is a static private method of the interface");
}
}
public class InterfaceMethodsExample implements MyInterface {
public void demo() {
System.out.println("Implementation of the demo method");
}
public static void main(String[] args){
InterfaceMethodsExample obj = new InterfaceMethodsExample();
obj.defaultMethod();
obj.demo();
MyInterface.staticMethod();
}
}
Kết quả đầu ra
This is a private method of the interface This is a static private method of the interface This is a default method of the interface Implementation of the demo method This is a static private method of the interface This is a static method of the interface
Quy tắc quan trọng
- Private method trong interface không thể là abstract.
- Private instance method chỉ được gọi từ các
default methodtrong cùng interface. - Private static method có thể được gọi từ
default methodvàstatic methodtrong cùng interface. - Private method không được kế thừa bởi lớp triển khai (implementing class) hay interface con (sub-interface).