2015-03-01 3 views
1

В этом коде я понимаю возвращаемое значение всего, кроме запроса (m). Почему запрос (m) печатает один вместо двух? Разве это не будет разрешено во время выполнения, что m имеет тип Winter. И тогда не следует печатать два?Динамическое связывание Java

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 

ответ

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

в

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 
+0

Ой, хорошо. Таким образом, в этом случае мы перегружаемся, поэтому требуется объявленный тип, который в этом случае является Сезон. Но если бы мы переопределили, в Runtime было бы понятно, что этот тип - Зима. Это верно? – aaa

+0

Я обновил свой ответ. Надеюсь, теперь это ясно. – Pshemo

Смежные вопросы