Override the protected method and try calling it from the superclass

My question comes from the project. So let me take my mind off a few unrelated details.

I have a public JAVA A class that has two protected static methods, foo () and bar (). The foo () method 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 redefine bar ()

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

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

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

I cannot understand two points 1. The compiler (Eclipse) asks me to remove the @Override annotation. What for? 2. Finally, main () prints "A.bar ()", which means that the target of resolved bar () has class A, but I decided to override bar () and use A foo () to call the modified string (). How can i do this?

What are your opinions?

+2
source share
2 answers
  • You cannot override static methods.
  • Since each method is static, it refers to them statically. You first call A.foo() , which in turn calls A.bar() . Since you do not have instances, method overriding does not work.

You need to remove all static from your code and use new B().foo() in your main folder.

Think about this tutorial .

+7
source

You cannot override static methods, only non-static instance methods. You are trying to use inheritance in a static environment and this will not work. If you really need inheritance (and often when you think you are doing this, you really are not), then make the methods non-static.

+6
source

Source: https://habr.com/ru/post/914972/


All Articles