Trong Java 9, interface cũng có thể có phương thức private (private methods). Bên cạnh static và default methods của Java 8, đây là thay đổi quan trọng khác cho phép tái sử dụng mã chung (re-usability of common code) bên trong chính interface.
Trong interface, có khả năng viết mã chung trên nhiều default method dẫn đến trùng lặp mã (code duplication). Việc giới thiệu private method tránh được việc trùng lặp này.
Ưu điểm của private method trong interface:
- Tránh trùng lặp mã (Avoiding code duplication).
- Đảm bảo tái sử dụng mã (Ensuring code re-usability).
- Cải thiện đọc hiểu mã (Improving code readability).
Cú pháp
interface interfacename {
private methodName(parameters) {
// statements
}
}
Ví dụ
interface Test {
default void m1() {
common();
}
default void m2() {
common();
}
private void common() {
System.out.println("Tutorialspoint");
}
}
public class PrivateMethodTest implements Test {
public static void main(String args[]) {
Test test = new PrivateMethodTest();
test.m1();
test.m2();
}
}
Kết quả
Tutorialspoint Tutorialspoint