Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java 9부터 인터페이스에서 private 메서드를 사용할 수 있을까?

네, Java 9부터는 인터페이스(interface) 안에서 private 메서드를 사용할 수 있습니다.

인터페이스에 private 메서드가 도입된 이유

Java 8에서 인터페이스에 default 메서드와 static 메서드가 추가되면서, 여러 메서드 사이에서 중복되는 로직을 공유해야 할 필요성이 생겼습니다. Java 9에서 도입된 private 메서드는 이러한 중복 코드를 제거하고, 인터페이스 내부에서만 재사용할 수 있는 공통 기능을 캡슐화하는 역할을 합니다.

private 메서드는 인터페이스를 구현하는 클래스나 외부에서 직접 호출할 수 없으며, 오직 해당 인터페이스 내부의 default 메서드나 static 메서드에서만 접근할 수 있습니다. private 메서드는 일반 형태와 static 형태 두 가지로 선언할 수 있습니다.

예제 코드

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();
    }
}

실행 결과

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

코드 설명

위 예제에서 defaultMethod()는 인스턴스 private 메서드인 privateMethod()와 static private 메서드인 staticPrivateMethod()를 모두 호출할 수 있습니다. 반면 staticMethod()는 static private 메서드만 호출할 수 있다는 점에 유의하세요. 실행 결과를 보면 default 메서드와 static 메서드가 각각 내부의 private 메서드를 성공적으로 호출하며, 구현 클래스에서는 이 private 메서드들에 전혀 접근할 수 없음을 알 수 있습니다.