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)
它是可访问的,但仅限于它自己的变量.