java存取權限的問題,java存取權限問題

來源:互聯網
上載者:User

java存取權限的問題,java存取權限問題
java存取權限的問題java存取權限修飾符背景:

關於java中的四種存取修飾詞,public ,default ,protected ,private的作用範圍本以為很熟悉了,但碰到了這樣一段代碼:

package pac1;public class Parent {    protected int i;    protected class Inner{           }}package pac2;import pac1.Parent;public class Child extends Parent {    public static void main(String args[]){        new Child().i=0;        Inner i = new Parent().new Inner();    }}
問題

代碼的意思是,父類與子類不在一個包,父類中有protected的內部類,現在想在子類中產生父類中內部類對象。但是發現報這錯誤:

Error:(8, 28) java: Inner()可以在pac1.Parent.Inner中訪問protected
思考

protected的存取權限是這說的,同一個包下是可以隨意訪問的,其他包下只有之類可以訪問。的確Inner i = new Parent().new Inner();左邊是沒有問題的,但是右邊是內部類產生方法,為什麼不能訪呢?
原來我在這裡只考慮了Parent和Child的包位置和繼承關係,而沒有考慮內部類和Child也是不同包,而Inner的建構函式存取權限不為public,因此在不同包又沒有繼關係的Child是不能產生Inner的。

解決

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.