2013-06-12 2 views
6

이 문제에 대한 토론이 필요하지만 제 경우에 대한 답을 추측 할 수 없습니다. 여전히 도움이 필요합니다. 여기 Java : 확장 하위 클래스에서 수퍼 클래스의 보호 된 멤버에 액세스 할 수 없습니다.

내 코드입니다 :

package JustRandomPackage; 

public class YetAnotherClass{ 
    protected int variable = 5; 
} 
package FirstChapter; 

import JustRandomPackage.*; 

public class ATypeNameProgram extends YetAnotherClass{ 
    public static void main(String[] args) { 

     YetAnotherClass bill = new YetAnotherClass(); 
     System.out.println(bill.variable); // error: YetAnotherClass.variable is not visible 

    } 
} 

의 예는 위의 혼란을 것 같다, 일부 정의 다음 :

1. Subclass is a class that extends another class. 
2. Class members declared as protected can be accessed from 
    the classes in the same package as well as classes in other packages 
    that are subclasses of the declaring class. 

질문

: 왜 수 없습니다 하위 클래스 YetAnotherClass 인스턴스 ()에서 보호 된 멤버 ( int variable = 5)에 액세스합니다.개체)?

+1

무엇이 문제입니까? –

답변

3

선언 클래스의 서브 클래스 인 다른 패키지의 클래스는 자신의 상속 된 protected 멤버에만 액세스 할 수 있습니다.

public class ATypeNameProgram extends YetAnotherClass{ 
    public ATypeNameProgram() { 
     System.out.println(this.variable); // this.variable is visible 
    } 
} 

... 그러나 다른 객체의 상속 된 protected 회원은 아닙니다.

public class ATypeNameProgram extends YetAnotherClass{ 
    public ATypeNameProgram() { 
     System.out.println(this.variable); // this.variable is visible 
    } 

    public boolean equals(ATypeNameProgram other) { 
     return this.variable == other.variable; // error: YetAnotherClass.variable is not visible 
    } 
} 
+0

잘못되었습니다. 이 코드는 컴파일됩니다. 다른 패키지의 클래스는 클래스 자체와 동일한 유형의 상속 된 보호 된 멤버에만 액세스 할 수 있습니다. –

1

청구서는 하위 클래스 YetAnotherClass의 일부가 아닙니다. 청구서는 별도의 YetAnotherClass입니다.

(생성자 내부에서) int bill = this.variable;을 시도하여 하위 클래스 '멤버에 액세스합니다.

0

확장하는 클래스의 인스턴스가 아니라 상위 클래스의 인스턴스를 만듭니다. 아래의 코드를 확인하십시오 YetAnotherClassATypeNameProgram와 같은 패키지에있을 것입니다 경우

public class ATypeNameProgram extends YetAnotherClass{ 
    public static void main(String[] args) { 

     YetAnotherClass bill = new YetAnotherClass(); 
     System.out.println(bill.variable); // error: YetAnotherClass.variable is not visible 

     ATypeNameProgram a = new ATypeNameProgram(); 
     System.out.println(a.variable); //this will work 

    } 
} 
1

귀하의 코드가 작동합니다. 다른 사람들이 쓴대로 다른 경우에는 작동하지 않습니다. 다음은 실제 예제입니다. 그리고 경우에만 BarFoo에 할당 할 경우

package my.example; 

public class MainClass extends MyAnotherClass { 
    public static void main(String[] args) { 
     MyAnotherClass bill = new MyAnotherClass(); 
     System.out.println(bill.value); // this will work 
    } 
} 

package my.example; 

public class MyAnotherClass { 

    protected int value = 5; 

} 
1

클래스 Foo는 유일한 유형 Bar의 보호 인스턴스 멤버에 액세스 할 수 있습니다. 즉, 우리가 쓸 수있는 경우 :

예를 들어
Foo foo = new Bar(); 

, 우리가 말 :

package a; 

public class Base { 
    protected int protectedField; 
} 

그리고 우리가 이것을 할 수 있습니다 :

package b; 

import a.Base; 

public class Parent extends Base { 
    void foo() { 
     int i = this.protectedField; 
    } 
    void foo(Parent p) { 
     int i = p.protectedField; 
    } 
    void foo(Child c) { 
     int i = c.protectedField; 
    } 
} 

class Child extends Parent { } 

이 컴파일 모든 protectedField의가 액세스 할 수 있기 때문에 Parent을 통해 Parent 참조는 Child 인스턴스 (예 : Parent p = new Child();이라고 작성할 수 있음) 일 수 있으므로 c.protectedField에 액세스 할 수 있습니다.

다음 것이다 하지 컴파일 :

package b; 

import a.Base; 

public class Parent extends Base { 
    void foo(Stepchild sc) { 
     int i = sc.protectedField; // ERROR 
    } 
} 

class Stepchild extends Base {} 

Stepchild의 인스턴스가 Parent의 인스턴스가 아닌 때문이다.

는 다소 혼동이 컴파일되지 않습니다 중 하나

package b; 

import a.Base; 

public class Parent extends Base {} 

class Child extends Parent { 
    void foo(Parent p) { 
     p.protectedField; // ERROR 
    } 
} 

Parent 객체가 Child의 슈퍼 클래스 나 슈퍼가 아닌, 그래서 Child이 보호 된 멤버에 액세스 할 수 있기 때문입니다.

기억하는 데 어려움이 있다면 유형을 수업 유형에 대한 참조에 쓸 수 있는지 생각해보십시오.

Parent p = new Child(); 

을하지만

Child c = new Parent();  // ERROR 
Parent p = new Stepchild(); // ERROR 

그렇게 ChildParent에 액세스 할 필요가 없습니다 쓸 수 없습니다 's의 보호 회원 및 ParentStepchild에 액세스 할 필요가 없습니다's의 보호 회원 : 예, 우리는 쓸 수 .

몇 최종 포인트 :

protected 액세스 패키지 중 가시성을 수 있다는 점을 기억하십시오. 제 경험상 사람들은 이것을 잊어 버립니다.

마지막으로 protected static 구성원은 상속 계층 구조에서 항상 볼 수 있습니다.