13

So here it is this example

public static void main(String[] args) {        
    new Stuff(null);
    new Stuff("a");
    new Stuff(1);           
}

and class Stuff is defined as follow

public class Stuff {    
       Stuff(Object o){
           System.out.println("object");        
       }

       Stuff(String s){
           System.out.println("string");        
       }

}

The output is

string
string
object

How does Java tell the null is a String? If I change Stuff to

public class Stuff {    

       Stuff(String s){
           System.out.println("string");        
       }

       Stuff(Integer o){
           System.out.println("Integer");           
       }

}

I get compilation error for Stuff(null):

The constructore Stuff(String) is ambigous. 

Again, why does Java "decide" null is a String?

Paolo
  • 2,461
  • 5
  • 31
  • 45
  • 1
    Because String is the closest thing to `null` among all others: "*The Java programming language uses the rule that the most specific method is chosen*". – Maroun Feb 16 '14 at 11:14
  • 2
    Worth mentioning that `null` is not a string, or an object, or an integer. (It's just the explicit lack of them). – Benjamin Gruenbaum Feb 16 '14 at 11:16
  • 1
    Since the comment isn't generated: Possible duplicate of http://stackoverflow.com/q/13033037/1864167 – Jeroen Vannevel Feb 16 '14 at 11:32

2 Answers2

19
  • The compiler first lists all applicable methods. In your case, both are applicable.
  • It then tries to find a method which is more specific than the other(s).
  • In your first example, String is a subclass of Object and is therefore more specific.
  • In your second example, both methods are applicable (String and Integer) but neither is more specific than the other (String is not a subclass of Integer which is not a subclass of String). So there is an ambiguity, hence the compiler error.

The full algorithm to determine which method should be chosen is defined in the JLS.

assylias
  • 321,522
  • 82
  • 660
  • 783
6

Because String is more specific then Object. Java always tries to use more specific match when figuring out which constructor or method to use.

celezar
  • 442
  • 3
  • 9