是否可以覆盖派生类中的静态方法? [英] Is it possible to override a static method in derived class?
本文介绍了是否可以覆盖派生类中的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个在基类中定义的静态方法,我想在其子类中覆盖此方法,是否可能?
I have a static method defined in a base class, I want to override this method in its child class, is it possible?
我试过这个但它确实不按我的预期工作。当我创建一个B类实例并调用它的callMe()方法时,调用A类中的静态foo()方法。
I tried this but it did not work as I expected. When I created an instance of class B and invoke its callMe() method, the static foo() method in class A is invoked.
public abstract class A {
public static void foo() {
System.out.println("I am base class");
}
public void callMe() {
foo();
}
}
Public class B {
public static void foo() {
System.out.println("I am child class");
}
}
推荐答案
静态方法调用在编译时解析(无动态调度)。
Static method calls are resolved on compile time (no dynamic dispatch).
class main {
public static void main(String args[]) {
A a = new B();
B b = new B();
a.foo();
b.foo();
a.callMe();
b.callMe();
}
}
abstract class A {
public static void foo() {
System.out.println("I am superclass");
}
public void callMe() {
foo(); //no late binding here; always calls A.foo()
}
}
class B extends A {
public static void foo() {
System.out.println("I am subclass");
}
}
给出
I am superclass
I am subclass
I am superclass
I am superclass
这篇关于是否可以覆盖派生类中的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文