What is the result of compiling and running the following code:

public class Main {
    public static void main(String[] args) {
        Parent p = new Parent();
        Child c = new Child();
        Parent p2 = new Child();

        useIt(p);
        useIt(c);
        useIt(p2);
    }

    final static void useIt (Parent p){
        System.out.println("Parent");
    }

    final static void useIt (Child c){
        System.out.println("Child");
    }
}

class Parent { }
class Child extends Parent { }
Explanation
Compiler chooses which overloaded method to use based on the type of a given reference, the type of object at runtime doesn't matter.

I think the explanation is a bit confusing. "Compiler chooses which overloaded method to use based on the type of a value (not reference) that contains the reference to an object (the value p2 has type Parent) but the object has type Child." - it is more accurate.

2023 Jun 14, 5:12:21 AM

Следи за CodeGalaxy

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

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