java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java访问修饰符

Java访问修饰符原理及代码解析

作者:main(0)

这篇文章主要介绍了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);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文