java中protected的权限
首先说明:父类和之类在不同包中,那么父类中的default和private方法都不能被子类继承。
java中protected
1. protected 访问控制符能被用于方法和成员变量。
2. 声明为protected的方法和成员变量能被同一个包里的所有类所访问,就像默认修饰符package一样。
3. 能被该类的子类所访问,子类可以和父类不在一个包中。
这样,当你想让一个类中的某个方法或成员变量在包中都可见,而且其子类也能访问(子类有可能和父类不在同一个包中)但又不想让所有类都可以访问该类时,就可以用protected修饰符。
可访问性:
public > protected > package >private
注意:
4. But a subclass in another package can access the protected members in the super-class via only the references of subclass or its subclasses. A subclass in the same package doesn’t have this restriction. This ensures that classes from other packages are accessing only the members that are part of their inheritance hierarchy.
下面的例子可以说明上述几点:(特别注意第4点)
我们将创建一个父类Bird.java,放在birdpack包中,父类中有一个protected int的成员变量nFeathers;
再分别创建4个Bird类的子类Duck1.java,Duck2.java,Duck3.java,Swan.java,放在duckpack包中,通过在每个子类中调用nFeathers的不同方法说明上述几点
下面的程序并不用于运行,因为访问控制在编译期间就要确定,我们只需编译下述文件,看是否能通过。在编译下述文件前,先想想能不能编译通过?

浙公网安备 33010602011771号