简体   繁体   English

当Child类覆盖受保护的成员时,该成员将可以使用访问。 操作员?

[英]When Child class override a protected member then member become access able with . operator?

package xxx.yyy;

 public class ParentClass { protected void doPrint(){ System.out.println("Parent....."); } } package aaa.bbb; import cathy.inner.ParentClass; public class Child extends ParentClass { public void getName(){ System.out.println("Child...."); } } 

A client in package aaa.bbb can not uses new Child().doPrint(). 软件包aaa.bbb中的客户端不能使用new Child()。doPrint()。 But if child override the then client can use new Child().doPrint(). 但是,如果子项被覆盖,则客户端可以使用新的Child()。doPrint()。 It seems strange to me because during override we can't change the access modifier to more restrictive, but is this case inherited method seems private. 对我来说,这很奇怪,因为在覆盖过程中,我们无法将访问修饰符更改为更严格的限制,但是这种情况下继承的方法似乎是私有的。

Why this is implemented in such a manner ? 为什么以这种方式实现?

Super class method's access modifier is protected and it states method would be accessible with in class , package and subclass . Super类方法的访问修饰符被protected ,它规定的方法是在访问classpackagesubclass

So it is not accessible in subclass's package . 因此,不能在子类的package中访问它

when you override that particular method in subclass with protected access modifier then it would accessible as protected methods are accessible under same package . 当您在subclass使用protected access修饰符覆盖该特定方法时,它将可以访问,因为protected方法可以在同一package下访问。

受保护将仅允许子类访问方法...这并不奇怪,它是Java具有的一种限制类型...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM