您好,登錄后才能下訂單哦!
這篇文章主要用代碼解析Java如何訪問修飾符,內容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
一、概述
訪問等級比較: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); } }
以上就是關于用代碼解析Java如何訪問修飾符的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。