简体   繁体   English

覆盖受保护的方法,并尝试从超类中调用它

[英]Override a protected method, and try to call it from the super class

My question comes from a project. 我的问题来自一个项目。 So let me abstract away a bit unrelated details. 因此,让我抽象出一些不相关的细节。

I have a JAVA public class A that has two protected static methods, foo() and bar(). 我有一个JAVA公共类A,它有两个受保护的静态方法,foo()和bar()。 The method foo() calls bar() in its body. 方法foo()在其体内调用bar()。

public class A{
  protected static foo(){
     ...
     bar()
     ...
  }
  protected static bar(){print("A.bar()");}

} 

Now I also have a class B extending A. In B, I override bar() 现在我还有一个B级扩展A.在B中,我重写bar()

class B extends A{
  @Overrides
  static protected bar(){ print("A.bar() extended");

}

Finally, I call foo() from a class in B 最后,我从B中的一个类调用foo()

class B extends A{
  ...
  public static main(){foo()} 
}

I cannot understand two points 1. The compiler (Eclipse) asks me to remove @Override annotation. 我无法理解两点1.编译器(Eclipse)要求我删除@Override注释。 Why? 为什么? 2. Finally the main() outputs "A.bar()", which means the resolved bar() target is of class A, but I intended to override bar() and use the A's foo() to call the modified bar(). 2.最后main()输出“A.bar()”,这意味着已解析的bar()目标是A类,但我打算覆盖bar()并使用A的foo()来调用修改后的bar( )。 How can I do that? 我怎样才能做到这一点?

What are your opinions? 你有什么看法?

  1. You cannot override static methods. 您无法覆盖静态方法。
  2. Since every method is static it refers to them statically. 由于每个方法都是静态的,因此静态引用它们。 You first call A.foo() which in turn calls A.bar() . 你首先调用A.foo() ,然后调用A.bar() Since you don't have instances, overriding methods does not work. 由于您没有实例,因此覆盖方法不起作用。

You need to remove all the static from your code and use new B().foo() in your main. 您需要从代码中删除所有static ,并在main中使用new B().foo()

Consider reading this tutorial . 考虑阅读本教程

You can't override static methods, only non-static instance methods. 您不能覆盖静态方法,只能覆盖非静态实例方法。 You're trying to use inheritance in a static environment, and that won't work. 您试图在静态环境中使用继承,但这不起作用。 If you truly need inheritance (and often when you think you do, really you don't), then make the methods non-static. 如果你真的需要继承(通常当你认为你做的时候,你真的没有),那么使这些方法非静态。

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

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