public class UnSafeSequence {
public class TestMath{
private TestMath(){
System.out.println("父类实例化");
}
}
public class TestMath1 extends TestMath{
public TestMath1(){
System.out.println("子类实例化");
}
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(new UnSafeSequence().new TestMath1());
}
}
java6語言規範中關於private修飾符的描述,頂層類別及內部類別的定義
6.6.1 if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the decocration的成員或建構器宣告為private的,那麼只有宣告這個成員或建構器的頂層類別才有權存取(當然宣告這個成員和建構子的類別也是可以存取的)
8.
A top level class is a class that is not a nested class. A nested class is any class whose declaration occurs within the body of another class or interface. A top stedlevel is class class a . 頂層類別不是一個巢狀類別(內部類別),巢狀類別(內部類別)是申明在其他類別或介面中的類別
java6語言規範中關於private修飾符的描述,頂層類別及內部類別的定義
鑑於上述的規定描述,那麼外部類別中可以存取構造器標示為private的TestMath內部類別。TestMath1同樣是一個內部類,其繼承了另一個內部類TestMath,因為一個內部類依賴外部類實例對象而存在,會隱式的關聯一個外部類實例
可以寫成所以
一般來說,子類別不可以呼叫父類別的私有建構方法。
你這裡這兩個類別都是同一個類別的成員內部類,內部類別可以自由地存取外部類別的成員變量,即使是private的。所以一個成員內部類別中可以存取另一個成員內部類別(因為它可以看成是一個成員變數),而被存取的成員內部類別對存取它的成員內部類別完全不設防。
內部類別本來就可以存取任意外部類別的私有方法和字段,TestMath1繼承的TestMath本身就是UnSafeSequence的內部類,所以TestMath1能夠存取UnSafeSequence裡定義的任何私有方法和字段包括了TestMath裡的私有方法和字段。
如果你把TestMath單獨定義在UnSafeSequence外面,那麼TestMath1就不能訪問TestMath裡的私有方法和字段了。