0

The code below really confused me. The output is "int array", but if I quote the second Confusing function, the output will be "Obejct". I wonder what null really means in Java.

And also why the Confusing class is created with calling the second constructor while not the first constructor

Why the compiler will call that constructor as it always calls the lowest extension of a class

public class Confusing {

    public Confusing(Object o){
        System.out.println("Obejct");
        if(o instanceof Object)
            System.out.println("Object");
    }

    public Confusing(int[] iArray){
        System.out.println("int array");
        if(iArray instanceof int[])
            System.out.println("Array");
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new Confusing(null);
    }

}
lhan
  • 23
  • 1
  • 5
  • 3
    http://stackoverflow.com/questions/2707322/what-is-null-in-java – R R Dec 09 '13 at 10:07
  • Null means nothing, you can pass nothing instead of any object, but it's rarely a good idea unless the method is expecting it – Richard Tingle Dec 09 '13 at 10:08
  • Why you have to check if it is an `instanceof`? Doesn't `type hinting` already does that? – giannis christofakis Dec 09 '13 at 10:08
  • [http://stackoverflow.com/questions/1894149/is-null-an-object](http://stackoverflow.com/questions/1894149/is-null-an-object) – onionpsy Dec 09 '13 at 10:08
  • @user3082297 this works, because int[] extends Object so the compiler will call that constructor as it always calls the lowest extension of a class (sorry don't know how to explain this well). Now if you change the `Object` to `String` you will get an ambigious error, as int[] doesn't extend String and therefore the compiler doesn't know which constructor to call. This you can fix by casting null: `new Confusing((String) null)` or `new Confusing((int[]) null)`. I wanted to add an answer with nice formatting, but unfortunately this question was blocked... – Blub Dec 09 '13 at 10:15
  • Thanks a lot. I think I know how it works now, but is there anyone who can told me why the compiler will call that constructor as it always calls the lowest extension of a class. – lhan Dec 09 '13 at 10:20

1 Answers1

3

null is not an object, it's a reference, see JLS:

There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type

Maroun
  • 94,125
  • 30
  • 188
  • 241