[java] 상위 클래스와 하위 클래스의 멤버 접근 제한

자바에서는 클래스 간의 상속 관계에서 멤버 변수와 메서드의 접근 제한에 대한 규칙이 있습니다. 상속을 받는 **하위 클래스(subclass)는 상위 클래스(superclass)의 멤버를 어떻게 접근할 수 있는지에 대한 이해가 필요합니다.

멤버 변수의 접근 제한

자바에서 멤버 변수의 접근 제한은 private, protected, default, public의 네 가지로 구분됩니다.

메서드의 접근 제한

메서드의 접근 제한은 멤버 변수와 동일하게 네 가지로 구분되며, 접근 범위 또한 유사합니다.

하위 클래스에서의 접근

하위 클래스는 상위 클래스의 protected 멤버와 public 멤버에 접근할 수 있습니다. private 멤버는 직접적으로 접근할 수 없지만, 상위 클래스의 public 또는 protected 메서드를 통해 간접적으로 접근할 수 있습니다.

예제 코드

public class SuperClass {
    private int privateVar;
    protected int protectedVar;
    int defaultVar;
    public int publicVar;

    private void privateMethod() {
        // private method implementation
    }

    protected void protectedMethod() {
        // protected method implementation
    }

    void defaultMethod() {
        // default method implementation
    }

    public void publicMethod() {
        // public method implementation
    }
}

public class SubClass extends SuperClass {
    public void accessSuperClassMembers() {
        int var1 = protectedVar; // 접근 가능
        int var2 = publicVar; // 접근 가능
        int var3 = defaultVar; // 접근 가능 (동일 패키지 내)
        // int var4 = privateVar; // 컴파일 오류 - private 멤버에 직접 접근 불가능
        // privateMethod(); // 컴파일 오류 - private 메서드에 직접 접근 불가능
        protectedMethod(); // 접근 가능
        defaultMethod(); // 접근 가능
        publicMethod(); // 접근 가능
    }
}

public class UnrelatedClass {
    public void accessSuperClassMembers(SuperClass superClass) {
        // int var1 = superClass.protectedVar; // 컴파일 오류 - 상속 관계가 아닌 클래스에서는 protected 멤버에 직접 접근 불가능
        int var2 = superClass.publicVar; // 접근 가능
        // int var3 = superClass.defaultVar; // 컴파일 오류 - 다른 패키지에서의 default 멤버 접근 불가능
        // superClass.protectedMethod(); // 컴파일 오류 - 상속 관계가 아닌 클래스에서는 protected 메서드에 직접 접근 불가능
        // superClass.defaultMethod(); // 컴파일 오류 - 다른 패키지에서의 default 메서드 접근 불가능
        superClass.publicMethod(); // 접근 가능
    }
}

상위 클래스와 하위 클래스 간의 멤버에 접근할 때에는 상속과 접근 제한자의 관계를 이해하는 것이 중요합니다.

자세한 내용은 Java 공식 문서를 참고하세요.