亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么子類可以調用父類的私有構造方法

為什么子類可以調用父類的私有構造方法

嗶嗶one 2019-03-22 15:15:10
查看完整描述

3 回答

?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

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 declaration of the member or constructor.

如果一個類的成員或構造器聲明為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 level class is a class that is not a nested class.

頂級類不是一個嵌套類(內部類),嵌套類(內部類)是申明在其他類或接口中的類


鑒于以上的規定描述,那么外部類中可以訪問構造器標示為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("子類實例化");

        }

    }

這樣就可以解釋一個內部類的子類為什么可以訪問其父類的私有的構造函數了


查看完整回答
反對 回復 2019-04-18
?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

一般來說,子類不可以調用父類的私有構造方法。
你這里這兩個類都是同一個類的成員內部類,內部類可以自由地訪問外部類的成員變量,即使是private的。所以一個成員內部類中可以訪問另一個成員內部類(因為它可以看成是一個成員變量),被訪問的成員內部類對訪問它的成員內部類完全不設防。

查看完整回答
反對 回復 2019-04-18
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

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

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


查看完整回答
反對 回復 2019-04-18
  • 3 回答
  • 0 關注
  • 1103 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號