Java修飾符public,protected,default,private存取權限

來源:互聯網
上載者:User

標籤:private   col   代碼   java   最大的   idt   自己   text   其他   

public

具有最大的存取權限。所有類可訪問。

protected

主要是用來保護子類。自身、子類及同一個包中類可以訪問

default

沒有加修飾符的。有時候也稱為friendly,它是針對本包訪問而設計的。同一包中可以訪問。

private

 存取權限僅限於類的內部,是一種封裝的體現。只能被自己訪問

  類內部 子類內部(本包) 其他類(本包) 子類內部(外部包) 其他類(外部包)
public O O O O O
protected O O O O X
default O O O X X
private O X X X X

 

 

 

 

 

範例程式碼

包apkg

ParentA.java

package apkg;public class ParentA {    public String publicVariable = "public";    protected String protectedVariable = "protected";    String variable = "default";    private String privateVariable = "privater";        public void show() {        System.out.println(this.publicVariable);        System.out.println(this.protectedVariable);        System.out.println(this.variable);        System.out.println(this.privateVariable);    }        public static void main(String[] args) {        ParentA apkg = new ParentA();        apkg.show();    }}

SonA.java

package apkg;public class SonA extends ParentA {    public void show() {        System.out.println(this.publicVariable);        System.out.println(this.protectedVariable);        System.out.println(this.variable);        //System.out.println(this.privateVariable);// 無法訪問    }}

UncleA.java

package apkg;import apkg.ParentA;public class UncleA {    public void show() {        ParentA apkg = new ParentA();        System.out.println(apkg.publicVariable);        System.out.println(apkg.protectedVariable);        System.out.println(apkg.variable);        //System.out.println(apkg.privateVariable);// 無法訪問    }}

包bpkg

SonB.java

package bpkg;import apkg.ParentA;public class SonB extends ParentA {    public void show() {        System.out.println(this.publicVariable);        System.out.println(this.protectedVariable);        //System.out.println(this.variable);// 無法訪問        //System.out.println(this.privateVariable);// 無法訪問    }}

UncleB.java

package bpkg;import apkg.ParentA;public class UncleB {    public void show() {        ParentA apkg = new ParentA();        System.out.println(apkg.publicVariable);        //System.out.println(apkg.protectedVariable);// 無法訪問        //System.out.println(apkg.variable);// 無法訪問        //System.out.println(apkg.privateVariable);// 無法訪問    }}

 

 

 

 

 

 

Java修飾符public,protected,default,private存取權限

聯繫我們

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