Java的Protected

Java的Protected

被声明为protected的变量、方法和构造方法能被同一个包中的任何其他类访问,也能够被不同包中的子类访问。

protected访问修饰符不能修饰类和接口,方法和成员变量能够声明为protected,但是接口的成员变量和成员方法不能声明为protected。

子类能访问protected修饰符声明的方法和变量,这样就能保护不相关的类使用这些方法和变量。

测试举例

//在A包中的基类
package WorkToOffer;

/**
 * Created by zhuhao on 17-6-3.
 */
public class TestBase {
    protected int protectInt=1;
    private int privateInt = 2;
    protected int getPortectInt(){
        return this.protectInt;
    }

}
//在B包中继承基类的子类
package LeetCode;

import WorkToOffer.TestBase;

/**
 * Created by zhuhao on 17-6-3.
 */
public class TestChild extends TestBase{
    //通过建立父类的对象测试
    public void testCrossPackage(){
        TestBase base = new TestChild ();
        //base.protectInt;  //跨包使用base中的protect实例变量失败
        //base.getPortectInt(); //跨包使用base中的protect方法失败
    }

    //直接通过继承Base的子类来测试
    public void testThroughClass(){
        protectInt = 666; //直接在类中访问正常
        System.out.println ("The protectInt now is "+getPortectInt ());
        super.protectInt = 777;//与上一行直接改变protectInt的值效果一样
        System.out.println ("The protectInt now is "+super.getPortectInt ());
    }

    //通过继承Base子类的对象做测试
    public void testThroughObject(){
        TestChild test = new TestChild ();
        test.protectInt =7676;  //通过TestChild的对象做测试,成功
        test.getPortectInt ();  //protected限定的实例变量和方法都通过测试
        System.out.println ("The protectInt now is "+getPortectInt ());
        //输出结果为1,表明父类没有受到影响
        System.out.println ("The protectInt now is "+test.getPortectInt ());
        //输出结果为7676,因为此实例变量的改变是绑定到对象test中的

    }


    public static void main(String[] args) {
        TestChild test = new TestChild ();
//        test.testThroughClass ();
        test.testThroughObject ();
    }
}

总结:

在父类中被protected修饰的实例变量和方法,在不同包中的使用时,其行为就像是子类自己的实例变量和方法一样,但是,不能在B包中通过建立Base类的对象去调用自己受保护的实例变量和方法。

参考1:网上的测试
参考2:java的访问控制符

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值