java - 为什么子类可以调用父类的私有构造方法
高洛峰
高洛峰 2017-04-17 17:50:33
0
3
417

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回覆(3)
洪涛
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 .
頂層類別不是一個巢狀類別(內部類別),巢狀類別(內部類別)是申明在其他類別或介面中的類別

鑑於上述的規定描述,那麼外部類別中可以存取構造器標示為private的TestMath內部類別。

TestMath1同樣是一個內部類,其繼承了另一個內部類TestMath,因為一個內部類依賴外部類實例對象而存在,會隱式的關聯一個外部類實例
所以

    public class TestMath1 extends TestMath{
        public TestMath1(){
            System.out.println("子类实例化");
        }
    }
可以寫成

    public class TestMath1 extends UnSafeSequence.TestMath{
        public TestMath1(){
            UnSafeSequence.this.super();
            System.out.println("子类实例化");
        }
    }
這樣就可以解釋一個內部類別的子類別為什麼可以存取其父類別的私有的建構函式了

刘奇

一般來說,子類別不可以呼叫父類別的私有建構方法。
你這裡這兩個類別都是同一個類別的成員內部類,內部類別可以自由地存取外部類別的成員變量,即使是private的。所以一個成員內部類別中可以存取另一個成員內部類別(因為它可以看成是一個成員變數),而被存取的成員內部類別對存取它的成員內部類別完全不設防。

大家讲道理

內部類別本來就可以存取任意外部類別的私有方法和字段,TestMath1繼承的TestMath本身就是UnSafeSequence的內部類,所以TestMath1能夠存取UnSafeSequence裡定義的任何私有方法和字段包括了TestMath裡的私有方法和字段。

如果你把TestMath單獨定義在UnSafeSequence外面,那麼TestMath1就不能訪問TestMath裡的私有方法和字段了。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板