자바의 protected 접근제어 수식어에 대한 이해
조회수 2022회
package1의 A라는 클래스와 package2의 C라는 클래스가 있습니다. 클래스 C는 A의 서브클래스입니다.
A는 인스턴스 필드 protectedInt
를 정의하였습니다:
protected int protectedInt = 1;
A 클래스:
package package1;
public class A {
public int publicInt = 1;
private int privateInt = 1;
int defaultInt = 1;
protected int protectedInt = 1;
}
C 클래스:
package package2;
import package1.A;
public class C extends A{
public void go(){
//remember the import statement
A a = new A();
System.out.println(a.publicInt);
System.out.println(a.protectedInt);
}
}
이클립승서 C.go() 메소드의 마지막 줄이 빨간줄이 생기고 "A.protectedInt"가 보이지 않는다는 에러 메시지를 발생합니다. "protected" 접근제어 지시자의 정의가 충돌된 것 같습니다. 다음의 오라클의 문서의 내용을 발췌한 것입니다.
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
왜그런건가요?
1 답변
-
왜 그런건가요?
protected
의 의미는 잘못 이해한 것 같습니다.C
또는C
의 서브클래스의 객체안에서A
에서 선언된 protected 멤버를 접근할 수 있습니다. protected 접근에 대한 자세한 사항을 section 6.6.2 of the JLS에서 확인해보세요. 특히 아래의 부분을요.Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C. In addition, if Id denotes an instance field or instance method, then:
- [...]
- If the access is by a field access expression E.Id, where E is a Primary expression, or by a method invocation expression E.Id(. . .), where E is a Primary expression, then the access is permitted if and only if the type of E is S or a subclass of S.
그래서 아래의 코드에는 에러가 없습니다:
C c = new C(); System.out.println(c.publicInt); System.out.println(c.protectedInt);
댓글 입력