gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:54:08 25 4
gpt4 key购买 nike

我在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com