java - 当我的子类位于不同的包中时,为什么我的子类无法访问其父类(super class)的 protected 变量?

标签 java package access-modifiers protected

我在database.relation包中有一个抽象类relation,在database包中有一个它的子类Join .操作relation 有一个名为 mStructure 的 protected 成员。

加入中:

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

上线

this.copyStructure(mRelLeft.mStructure);

for (final Header header : mRelRight.mStructure) {

我收到以下错误:

The field Relation.mStructure is not visible

如果我将两个类放在同一个包中,则效果非常好。谁能解释一下这个问题吗?

最佳答案

它可以工作,但只有您的 child 尝试访问它自己的变量,而不是其他实例的变量(即使它属于同一继承树)。

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

//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
    } 
}

如果我们尝试使用 withParent.parentVariable 进行编译,我们会得到:

Children.java:8: parentVariable has protected access in parentpackage.Parent
    System.out.print(withParent.parentVariable);

它是可访问的,但只能访问它自己的变量。

关于java - 当我的子类位于不同的包中时,为什么我的子类无法访问其父类(super class)的 protected 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57835192/

相关文章:

java - 克隆()不可见

java - 跨连接子类问题进行限制条件查询

android - PhoneGap - 市场上的无效应用程序

java - 如何编写 import 语句来引用 jar 中的 java 类?

java - 用于多个成员的单个 Java 访问修饰符

delphi - 将私有(private)/ protected /公共(public)方法设置为事件处理程序是否安全?

java - 在 Eclipse 插件运行时询问用户 "object"

r - 如何查找包所需的 R 版本

ios - 由于 'internal' 保护级别,初始化程序无法访问

java - 我的 Java 中的 pom.xml 文件在哪里?