在这段代码中,我了解了query(m)以外的所有内容的返回值。为什么query(m)打印一个而不是两个?在运行时不能确定m是Winter类型。然后不应该打印两个吗?

public class Season {
    public void weather() {
        System.out.println("cold");
    }
} // end class Season

public class Winter extends Season {
    public void weather() {
        System.out.println("freezing");
    }
} // end class Winter

public class QuizQuestion {

    public static void query(Season arg) {
        System.out.println("one");
    }

    public static void query(Winter arg) {
        System.out.println("two");
    }

    public static void main(String args[]) {
        Season s = new Season();
        Winter w = new Winter();
        Season m = new Winter();

        s.weather();
        w.weather();
        m.weather();
        query(s);
        query(w);
        query(m);
    } // end main
} // end class QuizQuestion

最佳答案

  Dynamic binding works for overriding  |  Static binding works for overloading
   (is based on actual instance type)   |      (is based on reference type)
----------------------------------------+-----------------------------------------
class Parent{                           | class Foo{
    public void method(){               |     void handle(Parent p){
        print("parent");                |         print("handling parent");
    }                                   |     }
}                                       |     void handle(Child c){
class Child{                            |         print("handling child");
    public void method(){               |     }
        print("child");                 | }
    }                                   |
}                                       | ...
...                                     | public static void main(String[] args){
public static void main(String[] args){ |     Parent p = new Child();
    Parent p = new Child();             |     Foo f = new Foo();
    p.method();//prints "child"         |     f.handle(p);//handling parent
}                                       | }


换句话说,它根据

s.weather(...)
^--------------this part




s.weather(...)
          ^^^--not this part


因此对于

Season s = new Season();
Winter w = new Winter();
Season m = new Winter();




s.weather(); //Season prints cold
w.weather(); //Winter prints freezing
m.weather(); //Winter prints freezing


但在这儿

query(s); //type of s reference (not instance) is Season
query(w); //type of w reference (not instance) is Winter
query(m); //type of m reference (not instance) is Season


因此,编译器只能决定使用引用类型(因为在运行时可以更改实际值),并且它为类型为参数的参数调用方法

Season -> one
Winter -> two
Season -> one

关于java - 动态绑定(bind)Java,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28798088/

10-08 23:54