多态性和静态方法 [英] Polymorphism and Static Methods
问题描述
我对此代码有疑问
public Car {
public static void m1(){
System.out.println("a");
}
public void m2(){
System.out.println("b");
}
}
class Mini extends Car {
public static void m1() {
System.out.println("c");
}
public void m2(){
System.out.println("d");
}
public static void main(String args[]) {
Car c = new Mini();
c.m1();
c.m2();
}
}
我知道多态不适用于静态方法,仅限实例方法。而且覆盖对静态方法也不起作用。
I know that polymorphism does not work with static methods, only to instance methods. And also that overriding doesn't work for static methods.
因此我认为这个程序应该打印出来:c,d
Therefore I think that this program should print out: c, d
因为c调用了m1方法,但它是静态的,所以它不能覆盖它并且它在类Mini而不是Car中调用方法。
Because c calls the m1 method, but it's static, so it can't override and it calls the method in class Mini instead of Car.
是这是正确的吗?
然而,我的教科书说答案应该是:a,d
However, my textbook says that the answer should be : a, d
是不是错字?因为我现在有点困惑。
is it a typo? Because I'm a little confused right now.
请清除它,谢谢。
推荐答案
因为c调用m1方法,但它是静态的,所以它不能覆盖和它在类Mini中调用方法而不是Car。
Because c calls the m1 method, but it's static, so it can't override and it calls the method in class Mini instead of Car.
这完全是倒退。
c
声明为 Car
,因此通过<$进行静态方法调用c $ c> c 将调用 Car
定义的方法。
编译器编译 c。 m1()
直接到 Car.m1()
,实际上并没有意识到 c
持有 Mini
。
c
is declared as Car
, so static method calls made through c
will call methods defined by Car
.
The compiler compiles c.m1()
directly to Car.m1()
, without being aware that c
actually holds a Mini
.
这就是你永远不应该通过像这样的实例调用静态方法的原因。
This is why you should never call static methods through instance like that.
这篇关于多态性和静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!