Java四種訪問修飾符

Java 四種訪問權限

1、概述

訪問等級比較:public > protected > default > private

不管是方法仍是成員變量,這四種訪問權限修飾符做用都同樣java

  • public:無論包外包內,全部類(子類+非子類)都可使用
  • protected
    • 包內:全部類可以使用
    • 包外:子類可以使用,非子類不可以使用
  • default
    • 包內:全部類可以使用
    • 包外:全部類不可以使用
  • private:僅本類可以使用

2、示例代碼

Test包內的父類Permissionthis

public class Permission {
    private int privateValue = 1;
    public int publicValue = 1;
    protected int protectedValue = 1;
    int defaultValue = 1;
    
    void defaultFunc(){
        System.out.println("This is a default function");
    }
    
    public void publicFunc(){
        System.out.println("This is a public function");
    }
    
    protected void protectedFunc() {
        System.out.println("This is a protected function");
    }

    private void privateFunc(){
        System.out.println("This is a private function");
    }
}

Test包內的子類SubPermissionspa

public class SubPermission extends Permission{
    public void permissionTest(){
        // public, protected, default function and variable can be used
        System.out.println("this is a default value:" +  this.defaultValue);
        System.out.println("this is a public value:" + this.publicValue);
        System.out.println("this is a protected value:" + this.protectedValue);

        this.publicFunc();
        this.protectedFunc();
        this.defaultFunc();
    }
}

Test包外的子類code

import base.Test.Permission;

public class Demo extends Permission {
    public static void main(String[] args) {
        // if is not a subclass, only public function and variable can be used
        Permission obj = new Permission();
        obj.publicFunc();
        System.out.println("this is a public value:" + obj.publicValue);

        // if is a subclass, public and protected function and variable can ba used
        Demo demo = new Demo();
        demo.publicFunc();
        demo.protectedFunc();
        System.out.println("this is a public value:" + demo.publicValue);
        System.out.println("this is a protected value:" + demo.protectedValue);
    }
}
相關文章
相關標籤/搜索