权限修饰符(public、protected、default、private)权限验证

本文通过具体示例详细解析了Java中private、protected等权限修饰符的作用范围,展示了不同类和包之间如何访问这些受权限保护的成员。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、测试方法

在authorityTest包中建类AuthorityValidate
package authorityTest;


public class AuthorityValidate {
    private String authority1 = "private";
    protected String authority2 = "protected";
    private void runPrivate(String a) {
        System.out.print(a);
    }
    protected void runProtectde(String b) {
        System.out.print(b);
        System.out.print(authority1);
    }
}

在authorityTest包中建立TheThirdClass类并尝试调用AuthorityValidate 中不同权限的方法

package authorityTest;

import testRun.ChildOfAut;


public class TheThirdClass {
    ChildOfAut a = new ChildOfAut();
    AuthorityValidate b = new AuthorityValidate();
    String c = b.authority2;
    String d = a.authority2;
    public static void main(String[] args) {
        AuthorityValidate b = new AuthorityValidate();
        ChildOfAut a = new ChildOfAut();
        System.out.print(b.authority2);
        System.out.print(a.authority2);
    }
}

 

在testRun包中建立ChildOfAut类继承AuthorityValidate 并尝试调用AuthorityValidate 中不同权限的方法

package testRun;

import authorityTest.AuthorityValidate;


public class ChildOfAut extends AuthorityValidate {
    
    public static void main(String[] args) {
        ChildOfAut a = new ChildOfAut();
        System.out.print(a.authority2);
        a.runProtectde("果然如此");
    }
}

在testRun包中建立TheOtherPackage类并尝试调用AuthorityValidate 中不同权限的方法

package testRun;

import authorityTest.AuthorityValidate;


public class TheOtherPackage {
    AuthorityValidate b = new AuthorityValidate();
    String a = b.authority2;
}


二、测试结果
TheThirdClass 类能调用AuthorityValidate 中protected修饰的属性和方法;
ChildOfAut类能调用AuthorityValidate 父类protected修饰的属性和方法;
TheOtherPackage类无法调用AuthorityValidate 父类protected修饰的属性和方法;
TheThirdClass,ChildOfAut,TheOtherPackage都不能访问AuthorityValidate 的private方法及属性;
以上,证明被protected修饰的属性、方法可被同一包中的类以及其子类访问。
被private修饰的属性、方法只能自身访问;
同理可证public可被任意类访问、default可被同一包中的类访问。
 

转载于:https://www.cnblogs.com/qcxdoit/p/9279286.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值