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

那年仲夏 提交于 2020-01-04 05:33:06

问题


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(). The method foo() calls bar() in its body.

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()

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

}

Finally, I call foo() from a class in B

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

I cannot understand two points 1. The compiler (Eclipse) asks me to remove @Override annotation. 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(). How can I do that?

What are your opinions?


回答1:


  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(). 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.

Consider reading this tutorial.




回答2:


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.



来源:https://stackoverflow.com/questions/10456561/override-a-protected-method-and-try-to-call-it-from-the-super-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!