java中訪問修飾符

來源:互聯網
上載者:User

標籤:div   addclass   function   string   子類   []   pop   void   static   

較之c++ 中 public,proctected, private 三種訪問控制, java多了預設訪問控制。


java中四種訪問控制許可權 簡單描寫敘述為一下四句:
1)private 僅本類可見 (同c++)
2)預設 對本包可見/包內訪問 (c++沒有)
3)protected 對本包和全部子類可見 (c++中沒有本包概念。較 預設訪問 能夠被在其它包下的子類訪問)
4)public 對全部類可見 (同c++)

當中1)4)與c++同樣,對2)3)做簡單測試

3)protected 對本包可見測試例如以下:

package com.behavior;public class Parent {    protected int i = 3;}
package com.behavior;//與Parent在同一個包下,無繼承關係public class Children {    public void action() {        Parent parent = new Parent();        System.out.print(parent.i);    }}
package com.stratege;import com.behavior.Children;public class ChildrenTest {        public static void main(String [] args) {            Children children = new Children();            children.action();        }}

驗證:protected 對包內訪問的許可權

2)預設 對包內訪問測試
將Parent中變數i 訪問許可權做例如以下改動,Children, ChildrenTest不變

package com.behavior;public class Parent {    int i = 3;}

驗證:預設對包內訪問的許可權

java中訪問修飾符

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.