Why can#39;t my subclass access a protected variable of its superclass, when it#39;s in a different package?(为什么我的子类不能访问其超类的受保护变量,当它位于不同的包中时?)
问题描述
我有一个抽象类 relation 在包 database.relation 和它的子类 Join 在包 database.操作代码>.relation 有一个名为 mStructure 的受保护成员.
I have an abstract class, relation in package database.relation and a subclass of it, Join, in package database.operations. relation has a protected member named mStructure.
在加入:
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) {
我收到以下错误:
Relation.mStructure 字段不可见
The field Relation.mStructure is not visible
如果我将两个类放在同一个包中,这将完美运行.谁能解释一下这个问题?
If I put both classes in the same package, this works perfectly. Can anyone explain this issue?
推荐答案
它有效,但只有你的孩子试图访问它 自己的变量,而不是其他实例的变量(即使它属于相同的继承树).
It works, but only you the children tries to access it own variable, not variable of other instance ( even if it belongs to the same inheritance tree ).
查看此示例代码以更好地理解它:
See this sample code to understand it better:
//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 进行编译,我们得到:
If we try to compile using the withParent.parentVariable we've got:
Children.java:8: parentVariable has protected access in parentpackage.Parent
System.out.print(withParent.parentVariable);
它是可访问的,但只能访问它自己的变量.
It is accessible, but only to its own variable.
这篇关于为什么我的子类不能访问其超类的受保护变量,当它位于不同的包中时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我的子类不能访问其超类的受保护变量,当它位于不同的包中时?
基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 大摇大摆的枚举 2022-01-01
