静态方法和多态 [英] static methods and polymorphism

查看:66
本文介绍了静态方法和多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题,我只是想不出一个好的答案.为什么下面的Java程序显示20?如果可能的话,我希望得到详细的答复.

I have a simple question that I just can't figure out a good answer for. Why does the following Java program display 20? I would prefer a detailed response if possible please.

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);
    }
}

推荐答案

静态方法的继承与非静态方法的继承工作方式不同.特别是超类静态方法不会被子类覆盖.静态方法调用的结果取决于调用它的对象类.变量x是在Something对象创建过程中创建的,因此会调用该类(Something)的静态方法来确定其值.

The inheritance for static methods works differently then non-static one. In particular the superclass static method are NOT overridden by the subclass. The result of the static method call depends on the object class it is invoke on. Variable x is created during the Something object creation, and therefore that class (Something) static method is called to determine its value.

考虑以下代码:

public static void main(String[] args){
  SomethingElse se = new SomethingElse();
  Something     sg = se;
  System.out.println(se.aMethod());
  System.out.println(sg.aMethod());
}

当每个对象类调用自己的静态方法时,它将正确打印 40、20.Java 文档在隐藏静态方法部分描述了这种行为.

It will correctly print the 40, 20 as each object class invokes its own static method. Java documentation describes this behavior in the hiding static methods part.

这篇关于静态方法和多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆