重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章主要用代码解析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如何访问修饰符的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。