Java 9 인터페이스의 private 메소드란?
Java 9부터 인터페이스(interface) 내부에 private 메소드를 정의할 수 있는 새로운 기능이 추가되었습니다. private 메소드는 private 한정자(modifier)를 사용해 선언하며, Java 9 이상에서는 일반 private 메소드와 private static 메소드를 모두 인터페이스 안에 작성할 수 있습니다.
이 기능은 인터페이스 내 여러 default 메소드나 static 메소드에서 공통 로직을 재사용하기 위해 도입되었습니다. 이전 버전에서는 인터페이스 내부에 중복 코드를 숨길 방법이 없었지만, private 메소드 덕분에 코드 중복을 줄이고 캡슐화를 강화할 수 있게 되었습니다.
인터페이스 private 메소드의 규칙
- 몸체(body)가 반드시 필요합니다. 인터페이스의 private 메소드는 일반 추상 메소드처럼 선언만 할 수 없습니다. 몸체 없이 선언하면 "This method requires a body instead of a semicolon"(세미콜론 대신 메소드 몸체가 필요합니다)라는 오류가 발생합니다.
- private와 abstract 한정자는 함께 사용할 수 없습니다.
- static 메소드에서 private 메소드를 호출하려면, 해당 메소드는 private static 메소드로 선언되어야 합니다. static 컨텍스트에서는 non-static 메소드를 참조할 수 없기 때문입니다.
- private static 메소드는 non-static 컨텍스트에서도 호출 가능합니다. 즉, 인터페이스의 default 메소드에서도 private static 메소드를 호출할 수 있습니다.
문법(Syntax)
interface <인터페이스명> {
private methodName(parameters) {
// 실행 문장
}
}예제 코드
interface TestInterface {
default void methodOne() {
System.out.println("This is a Default method One...");
printValues(); // private 메소드 호출
}
default void methodTwo() {
System.out.println("This is a Default method Two...");
printValues(); // private 메소드 호출
}
private void printValues() { // 인터페이스 내 private 메소드
System.out.println("methodOne() called");
System.out.println("methodTwo() called");
}
}
public class PrivateMethodInterfaceTest implements TestInterface {
public static void main(String[] args) {
TestInterface instance = new PrivateMethodInterfaceTest();
instance.methodOne();
instance.methodTwo();
}
}실행 결과
This is a Default method One...
methodOne() called
methodTwo() called
This is a Default method Two...
methodOne() called
methodTwo() called
정리
Java 9의 인터페이스 private 메소드는 default 메소드 간 중복 코드를 제거하고, 구현 세부사항을 외부에 노출하지 않으면서 재사용성을 높이는 강력한 기능입니다. 다만 위에서 살펴본 것처럼 몸체 필수, abstract 조합 불가, static 참조 규칙 등의 제약 조건을 반드시 지켜야 하므로, 실무에서 활용할 때 이러한 규칙을 숙지하는 것이 중요합니다.