What will be the result of compiling and running this code?

class A {}

interface I {}

class B extends A implements I {}

public class OverloadTest {
    static public  void foo(A a) { System.out.print("A"); }
    static private void foo(B b) { System.out.print("B"); }
    static private void foo(I i) { System.out.print("I"); }
    
    public static void main(String[] args) {        
        A a = new B();
        OverloadTest.foo(a);
        OverloadTest.foo((I) a);
    }

}
Explanation
For overloaded methods the decision which method to invoked is made in compile time, contrary to polymorphism when it is made in runtime.
1: Let's look at the OverloadTest.foo(a). Compiler does not know exact class of the variable 'a', it only knows the type of the variable 'a', namely A. Based on the type of the variable compiler decides to call the method foo(A a).
2: OverloadTest.foo((I) a). In this case compiler gets a clear indication that the argument is of type I, hence will be called foo(I i).

Another case is when the argument is specified as null, OverloadTest.foo(null). In this case the method will be called with an argument of the highest hierarchy type, in this case foo(B b).

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести