当我的子类位于不同的包中时,为什么我的子类不能访问其超类的受保护变量?

Ami*_*hum 31 java packages protected access-modifiers

我有一个抽象类,relation封装database.relation和它的一个子类,Join在包database.operations.relation有一个名为的受保护成员mStructure.

Join:

public Join(final Relation relLeft, final Relation relRight) {
        super();
        mRelLeft = relLeft;
        mRelRight = relRight;
        mStructure = new LinkedList<Header>();
        this.copyStructure(mRelLeft.mStructure);

        for (final Header header :mRelRight.mStructure) {
        if (!mStructure.contains(header)) {
            mStructure.add(header);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在线上

this.copyStructure(mRelLeft.mStructure);
Run Code Online (Sandbox Code Playgroud)

for (final Header header : mRelRight.mStructure) {
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

字段Relation.mStructure不可见

如果我把两个类都放在同一个包中,这样就可以了.有谁能解释这个问题?

Osc*_*Ryz 26

它起作用,但只有你的孩子试图访问它自己的变量,而不是其他实例的变量(即使它属于同一个继承树).

请参阅此示例代码以更好地理解它:

//in Parent.java
package parentpackage;
public class Parent {
    protected String parentVariable = "whatever";// define protected variable
}

// in Children.java
package childenpackage;
import parentpackage.Parent;

class Children extends Parent {
    Children(Parent withParent ){
        System.out.println( this.parentVariable );// works well.
        //System.out.print(withParent.parentVariable);// doesn't work
    } 
}
Run Code Online (Sandbox Code Playgroud)

如果我们尝试使用withParent.parentVariable我们得到的编译:

Children.java:8: parentVariable has protected access in parentpackage.Parent
    System.out.print(withParent.parentVariable);
Run Code Online (Sandbox Code Playgroud)

它是可访问的,但仅限于它自己的变量.


Mar*_*ams 13

关于受保护的一个鲜为人知的警告:

6.6.2受保护访问的详细信息

受保护的成员或对象的构造函数可以从包外部访问,只能通过负责实现该对象的代码来声明它.

  • 我发现§6.6.7下的例子在这里很有用. (2认同)