Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When sent to a constructor in Java, what does "null" value do? [duplicate]

Possible Duplicate:
Which constructor is chosen when passing null?

I recently came across this curiosity while coding a few days back and can't seem to figure out why the following happens:

Given the class below

public class RandomObject{
    public RandomObject(Object o){
        System.out.println(1);
    }
    public RandomObject(String[] s){ 
        System.out.println(2);
    }
}

When the call new RandomObject(null); is made the output is always 2 regardless of the order in which the constructors were created. Why does null refer to the string array rather than the object?

like image 640
Erik Nguyen Avatar asked Jan 25 '13 04:01

Erik Nguyen


1 Answers

The key here is that Object is the super type of String[]

Java uses the most specific available method to resolve such cases. Null can be passed to both methods without compilation errors so Java has to find the most specific method here. The version with String[] is more specific - therefore it will be chosen for execution.

like image 64
Andrey Taptunov Avatar answered Oct 19 '22 13:10

Andrey Taptunov