Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java: Общие вопросы > SCJP - Mock Test


Автор: Entwickler 14.11.2011, 15:14
Всем привет,

есть такой вопрос в Mock тесте на SCJP:

Number is the superclass over Integer, Float and so on.

What happens if you try to compile this code and run the method call() from the following class:

Код

public class Overload {

     String c;

     void m(Object o) {
          c = "Object";
     }

     void m(Number n) {
          c = "Number";
     }

     void m(Float f) {
          c = "Float";
     }

     void call() {
          m(null);
          System.out.println(c);
     }
}


Answers:

A - It prints Object
B - It prints Number
C - It prints Float
D - It prints Integer
E - It does not compile
F - It compiles, but leads to a RuntimeException


Правильный ответ: C. Почему?!!

Автор: jk1 14.11.2011, 15:43
Java Language Specification
Цитата

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.


То есть выбирается самый конкретный (most specific, расположеный ниже всего в иерархии наследования) из доступных вариантов. Поскольку Float extends Number extends Object самым конкретным будет Float. Ради интереса добавьте вариант Double - код перестанет компилироваться, ведь в этом случае уже нельзя будет подобрать наиболее конкретный вариант.

Автор: kemiisto 14.11.2011, 16:32
jk1, тут ещё важно, что тип данных null, null type, http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.10.2.
Цитата
The direct supertypes of the null type are all reference types other than the null type itself.

Автор: Entwickler 14.11.2011, 16:39
super jk1... огромное спасибо...

почитал так же: http://www.xyzws.com/Javafaq/what-is-a-mostspecific-method/8

Автор: Entwickler 14.11.2011, 17:57
Всем спасибо ещё раз!!! (забыл пометить как решённый)

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)