静态方法和多态性

2024-02-25

我有一个简单的问题,但我无法找到一个好的答案。为什么下面的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);
    }
}

因为多态只适用于实例方法。

The static method aMethod在这里调用

public Something(){
    x=aMethod();
}

指的是aMethod声明于Something.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

静态方法和多态性 的相关文章

随机推荐