重写受保护的方法,然后尝试从超类调用它 [英] 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.
我有一个JAVA公共类A,它具有两个受保护的静态方法foo()和bar(). foo()方法在其主体中调用bar().
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()");}
}
现在我还有一个扩展A的类B.在B中,我重写了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");
}
最后,我从B中的一个类调用foo()
Finally, I call foo() from a class in B
class B extends A{
...
public static main(){foo()}
}
我不明白两点 1.编译器(Eclipse)要求我删除@Override注释.为什么? 2.最终main()输出"A.bar()",这意味着已解决的bar()目标属于A类,但我打算重写bar()并使用A的foo()来调用修改后的bar( ).我怎样才能做到这一点?
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?
您对此有何看法?
推荐答案
- 您不能覆盖静态方法.
- 由于每种方法都是静态的,因此它是静态引用的.您首先呼叫
A.foo()
,后者又呼叫A.bar()
.由于您没有实例,因此覆盖方法不起作用.
- You cannot override static methods.
- Since every method is static it refers to them statically. You first call
A.foo()
which in turn callsA.bar()
. Since you don't have instances, overriding methods does not work.
您需要从代码中删除所有static
,并在其主体中使用new B().foo()
.
You need to remove all the static
from your code and use new B().foo()
in your main.
考虑阅读此教程.
这篇关于重写受保护的方法,然后尝试从超类调用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!