Question

The output of the given code is

ClassB

ClassA

class Main{

public static void main(String args){
new Main().getVal(null);  //which method will be called????

A obj=new B();
new Main().getVal(obj);  //which method will be called????

}

public void getVal(A o){
System.out.println("class A");
}

public void getVal(B o){

System.out.println("class B");
}

}

class A{

}

class B extends A{


}

So its clear that when null is passed then method with the most child as argument is called and in the second case the call defends on the reference type and not on the object created. Sp can anybody give me an explanation why this happens or what happens in java internally?

Was it helpful?

Solution

Java will attempt to find the most specific method available.

Null can be of any type, so the most specific method is the type B, so the first line that is printed is "class B".

For the second line, you have a variable of type A, and static binding is used to determine which method to call, so the second line prints "class A". With parameter types, polymorphism and dynamic binding is not used; it depends on the static type of the variables passed in.

Section 15.12.2.5 of the JLS states:

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.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top