动态绑定Java

时间:2015-03-01 19:32:59

标签: java dynamic binding

在这段代码中,我理解除query(m)之外的所有内容的返回值。为什么查询(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

1 个答案:

答案 0 :(得分:2)

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

in

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