Java访问修饰符原理及代码解析
程序员文章站
2022-07-06 17:47:25
一、概述访问等级比较:public > protected > default > private无论是方法还是成员变量,这四种访问权限修饰符作用都一样 public:不管包外包内...
一、概述
访问等级比较: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); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 经典:现在大家都是这么说的
下一篇: 分布式锁三种实现方式及对比