What is the result of the following code compilation and execution?

public class MainClass {
    public static void test(int ...a) {
        System.out.println("int...");
    }

    public static void test(Integer ...a) {
        System.out.println("Integer...");
    }

    public static void test(Number ...a) {
        System.out.println("Number...");
    }

    public static void main(String args[]){
        Number n = new Integer(1);
        test(n.intValue());
    }
}
Explanation
Each of the four methods is potentially applicable for test(int) call.
It is compiler's task in this case to choose the most specialized method.
In case of methods with variable number of arguments compiler considers how base types are related to each other and chooses the most narrow one while the actual parameter's type is ignored.
Thus, given the Integer and Number types, Integer will be the most narrow one. But primitive types are not reference types' subtypes, so compiler cannot determine the most narrow type from int and Integer types and it generates a compilation error.

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по Java
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты