【发布时间】:2013-05-26 20:32:25
【问题描述】:
我有这些课程:
package abc;
public class A {
public int publicInt;
private int privateInt;
protected int protectedInt;
int defaultInt;
public void test() {
publicInt = 0;
privateInt = 0;
protectedInt = 0;
defaultInt = 0;
}
}
“A”包含所有四个访问修饰符的属性。这些其他类扩展“A”或创建实例并尝试访问属性。
package de;
public class D {
public void test() {
E e = new E();
e.publicInt = 0;
e.privateInt = 0; // error, cannot access
e.protectedInt = 0; // error, cannot access
e.defaultInt = 0; // error, cannot access
}
}
package de;
import abc.A;
public class E extends A {
public void test() {
publicInt = 0;
privateInt = 0; // error, cannot access
protectedInt = 0; // ok
defaultInt = 0; // error, cannot access
}
}
package abc;
import de.E;
public class C {
public void test() {
E e = new E();
e.publicInt = 0;
e.privateInt = 0; // error, cannot access
e.protectedInt = 0; // ok, but why?
e.defaultInt = 0; // error, cannot access
}
}
一切正常,除了我不明白,为什么在 C 类中,我可以访问 e.protectedInt。
【问题讨论】:
标签: java inheritance protected