关于java中protected修饰符的重新认识

java四种访问修饰符:public、protected、default、private

关于protected的解释“This is private as far as the class user is concerned,

but available to anyone who inherits from this class or anyone else in the same package.”

先看一个例子,请注意包的细微差别!

//第一个类,a包下的Parent类,充当父类

package a;

public class Parent{

  protected Parent p = new Parent();

  public void test1(){}

  protected void test2(){}

  public static void test3(){}

  protected static void test4(){}

}

//第二个类,b包下的Son1类,充当a.Parent类的子类

package b;

import a.*;

public class Son1 extends Parent{

   public void test(){

      p.test1();

      p.test2();//编译错误,test2方法不可见

      Parent.test3();

      Parent.test4();//编译通过

   }

}


//第三个类,a包下的Son1类,充当a.Parent类的子类

package a;

public class Son2 extends Parent{

   public void test(){

      p.test1();

      p.test2();//编译通过

      Parent.test3();

      Parent.test4();//编译通过

   }

}


由此可见protected修饰的成员并非所有的类都可以访问,只有在同一个包中或者有继承关系的类中可见。

然而对继承关系的的理解也并非想象中的那么简单,从上述例子中可以看出,子类中并非可以自由的访问protected修饰的成员。事实上可以看成protected和default修饰符的功能基本相同,只不过protected提供了一种通过继承的方式访问成员的方法,从上述例子可见任意试图通过继承以外方法访问不同包中的protected修饰成员都是禁止的(比如,将Parent组合到Son1中)。重新理解“who inherits from this class”这句话,不禁感到意味深长。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值