Java訪問修飾符原理及代碼解析
一、概述
訪問等級(jí)比較:public > protected > default > private
無論是方法還是成員變量,這四種訪問權(quán)限修飾符作用都一樣
public:不管包外包內(nèi),所有類(子類+非子類)均可使用 protected 包內(nèi):所有類可使用 包外:子類可使用,非子類不可使用 default 包內(nèi):所有類可使用 包外:所有類不可使用 private:僅本類可使用二、示例代碼
Test包內(nèi)的父類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包內(nèi)的子類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); }}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 基于javascript處理二進(jìn)制圖片流過程詳解2. 解決android studio引用遠(yuǎn)程倉(cāng)庫(kù)下載慢(JCenter下載慢)3. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟4. ajax請(qǐng)求添加自定義header參數(shù)代碼5. ASP基礎(chǔ)知識(shí)VBScript基本元素講解6. 使用Python和百度語音識(shí)別生成視頻字幕的實(shí)現(xiàn)7. Kotlin + Flow 實(shí)現(xiàn)Android 應(yīng)用初始化任務(wù)啟動(dòng)庫(kù)8. idea刪除項(xiàng)目的操作方法9. 教你如何寫出可維護(hù)的JS代碼10. 使用python 計(jì)算百分位數(shù)實(shí)現(xiàn)數(shù)據(jù)分箱代碼
