Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining which method will be executed (Type system)

Tags:

java

I have a question concerning Java's Type system.

I have four classes A, B, AStar and BStar. AStar extends A and Bstar extends B.

On top of that I have another class that has the following methods:

public static void main(String[] args) {
    AStar a = new AStar();
    BStar b = new BStar();

    someMethod(a,b);
}   

public static void someMethod(A a,BStar b) {
    System.out.println("first");        
}

public static void someMethod(AStar a,B b) {
    System.out.println("second");
}

The implementation that is executed is the first one.

From my understanding, Java considers the static types of the arguments and chooses the signature that is most specialized ("fits best") as the signature of the method that will be called.

While this rule of thumb works most of the time, it fails in a few cases with the example above being the 'base case' (not involving polymorphism etc.)

I spent a considerable amount of time looking for an explanation of this behaviour (online as well as in the java books I have at disposal here), but did not find anything.

I would be very grateful for an explanation or a link to a resource that explains this behaviour...

Thanks in advance

Michael

like image 399
mSchwarz Avatar asked Oct 02 '22 03:10

mSchwarz


1 Answers

if you are using java 1.5 or before, you would be able to run the program. it was a noted bug which was later fixed with 1.6 and above.

have a look at this:

"method is ambiguous for the type" but the types are NOT ambiguous (and the error comes by upgrade from eclipse 3.7.2 to eclipse 4.2)

like image 126
Ashish Avatar answered Oct 13 '22 09:10

Ashish