简体   繁体   English

静态方法和多态

[英]static methods and polymorphism

I have a simple question that I just can't figure out a good answer for. 我有一个简单的问题,我无法找到一个好的答案。 Why does the following Java program display 20? 为什么以下Java程序显示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);
    }
}

Because polymorphism only applies to instance methods. 因为多态只适用于实例方法。

The static method aMethod invoked here 这里调用的static方法aMethod

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

refers to the aMethod declared in Something . 指的是在Something声明的aMethod

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. 变量x是在Something对象创建期间创建的,因此调用该类(Something)静态方法来确定其值。

Consider following code: 考虑以下代码:

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

It will correctly print the 40, 20 as each object class invokes its own static method. 当每个对象类调用自己的静态方法时,它将正确打印40,20。 Java documentation describes this behavior in the hiding static methods part. Java文档在隐藏静态方法部分中描述了此行为。

Because int x is declared in the class Something . 因为int x在类Something声明。 When you make the SomethingElse object, you first make a Something object (which has to set x, and it uses the aMethod() from Something instead of SomethingElse (Because you are creating a Something )). 当您创建SomethingElse对象时,首先创建一个Something对象(必须设置x,并使用SomethingaMethod()而不是SomethingElse (因为您正在创建Something ))。 This is because aMethod() is static, and polymorphism doesn't work for static methods. 这是因为aMethod()是静态的,而多态不适用于静态方法。 Then, when you print the x from m, you print 20 since you never changed the value of x. 然后,当您从m打印x时,打印20,因为您从未更改过x的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM