简体   繁体   English

覆盖父方法

[英]Overriding a parent method

I have a class A private method 1 我有一个A类私人方法1

class B extends A private method 1 (Same name) B类扩展私有方法1(同名)

When I instantiate B and method 1 gets called from class A. I made them both protected and that solved it. 当我实例化B时,方法1从类A调用。我使它们都受到保护并解决了它。 Is there a way to keep both private and still get class B's method 1 to be called? 有没有办法保持私有,仍然可以调用B类的方法1?

看一下java教程中可见性修饰符的这个解释,之后会很清楚

No. Private is designed for that class and that class alone. 不,私人是专门为那个班级和那个班级设计的。

Protected is designed for any subclesses to know about, use and override if required. 受保护的是为任何subclesses设计的,以便在需要时了解,使用和覆盖。

private methods are only accessible from that specific class so you can't override them. 私有方法只能从该特定类访问,因此您无法覆盖它们。 You can have method with same name and arguments in a subclass and there will be no errors, but it will not override it. 您可以在子类中使用具有相同名称和参数的方法,并且不会出现任何错误,但它不会覆盖它。

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

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