-2

Possible Duplicate:
Java method dispatch with null argument

Why does this print "a(String)"?

public class Test{
    public static void main(String[] args){
        a(null);
    }
    public static void a(Object x){
        System.out.println("a(Object)");
    }
    public static void a(String x){
        System.out.println("a(String)");
    }
    public static void a(int x){
        System.out.println("a(int)");
    }
    public static void a(){
        System.out.println("a()");
    }
}

Java version:

java version "1.7.0_04-ea"
Java(TM) SE Runtime Environment (build 1.7.0_04-ea-b228)
Java HotSpot(TM) 64-Bit Server VM (build 23.0-b12, mixed mode)
Community
  • 1
  • 1
wuntee
  • 12,170
  • 26
  • 77
  • 106

2 Answers2

2

Because the rule is to select the most specific method and String inherits from Object.

From the specification :

If several applicable methods have been identified during one of the three phases of applicability testing, then the most specific one is chosen

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

In case of overloaded methods compiler calls the method with most specific argument. As java.lang.String is more specific class than java.lang.Object compiler call's the method with string as argument.

From Java language Specification:

If several applicable methods have been identified during one of the three phases of applicability testing, then the most specific one is chosen

PermGenError
  • 45,977
  • 8
  • 87
  • 106