2

I have the following code

public class HelloWorld {

    public void printData (Test t) {
        System.out.println("Reached 1");
    }

    public void printData(NewTest t) {
        System.out.println("Reached 2");
    }

    public static void main(String args[]) {
        HelloWorld h = new HelloWorld();
        h.printData(null);
    }
}

and I have two simple classes

class Test {
}

class NewTest extends Test {
}

and the output I got is Reached 2

Why the second function was selected for executing and not the 1st one? Also when I tried the same code by making another class NewTest2 extending Test and analogous printData() function it gave me compile time error. Is there any rule to select which function must be executed and when?

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289

2 Answers2

6

Why the second function was selected for executing and not the 1st one?

Because the method taking NewTest is more specific than the method taking Test, and both are accessible and applicable.

However, when you've got two subclasses of Test, neither conversion is more specific than the other, hence the call is ambiguous.

See JLS section 15.12.2.5 for the exact rules involved:

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 type error.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

What IDE do you use ? In Eclipse "h.printData(null)" is marked red with this error:

The method printData(Test) is ambiguous for the type HelloWorld.

In this case you need to cast null like that:

"h.printData((Test)null)"