Java 四種訪問許可權 一、概述 訪問等級比較:public > protected > default > private 無論是方法還是成員變數,這四種訪問許可權修飾符作用都一樣 public:不管包外包內,所有類(子類+非子類)均可使用 protected 包內:所有類可使用 包外:子類可使用, ...
Java 四種訪問許可權
一、概述
訪問等級比較:public > protected > default > private
無論是方法還是成員變數,這四種訪問許可權修飾符作用都一樣
- public:不管包外包內,所有類(子類+非子類)均可使用
- protected
- 包內:所有類可使用
- 包外:子類可使用,非子類不可使用
- default
- 包內:所有類可使用
- 包外:所有類不可使用
- private:僅本類可使用
二、示例代碼
Test包內的父類Permission
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包內的子類SubPermission
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包外的子類
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);
}
}