我有这些类:爪哇 - 保护的访问修饰符
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。