我有這些類:爪哇 - 保護的訪問修飾符
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。