Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is ambiguity in selecting from overloaded methods resolved in Java?

Tags:

java

package org.study.algos;
public class Study {

    public static void main(String[] args) {
       A a = new A();
       a.m1(null);
    }
 }
 class A {
    public void m1(String s) {
       System.out.println("String");
        System.out.println(s);
    }
    public void m1(Object obj) {
       System.out.println("Object");
       System.out.println(obj);
    }
}

Here, the output is

String null

Why does the JVM resolve the method to one with a String argument?

Thanks in advance J

like image 402
Jijoy Avatar asked Apr 09 '10 14:04

Jijoy


People also ask

How do you handle ambiguity in Java?

Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict. Here is an example that involves method overloading. In this case, Java uses the type difference to determine which overloaded method to call.

What is ambiguity in method overloading in Java?

JavaServer Side ProgrammingProgramming. There are ambiguities while using variable arguments in Java. This happens because two methods can definitely be valid enough to be called by data values. Due to this, the compiler doesn't have the knowledge as to which method to call.


1 Answers

It's a fairly elaborate algorithm, detailed in JLS 15.12. But the part that is relevant here is 15.12.2, which says "the most specific one is chosen." Both the Object and String overloads are "accessible and applicable" (the String is applicable because a null literal is a reference of all types), and the String is more specific.

EDIT: Corrected section, per Syntactic.

like image 69
Matthew Flaschen Avatar answered Oct 04 '22 02:10

Matthew Flaschen