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

来源:互联网 发布:网站数据泄露防护 编辑:程序博客网 时间:2024/05/19 11:46

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
原创粉丝点击