我有一个简单的问题,但我想不出一个好的答案。为什么下面的Java程序显示20?如果可能的话,我希望得到详细的答复。
class Something{
public int x;
public Something(){
x=aMethod();
}
public static int aMethod(){
return 20;
}
}
class SomethingElse extends Something{
public static int aMethod(){
return 40;
}
public static void main(String[] args){
SomethingElse m;
m=new SomethingElse();
System.out.println(m.x);
}
}
最佳答案
因为多态只适用于实例方法。
这里调用了static
方法aMethod
public Something(){
x=aMethod();
}
指的是在Something
中声明的aMethod
。
关于java - 静态方法和多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28118392/