2

I have a Java class where there are two parameterized constructors

public class TestApplication {

    TestApplication(Object o)
        {
            System.out.println("Object");
        }

        TestApplication(double[] darray)
        {
            System.out.println("Array");
        }

        public static void main(String[] args)
        {
            new TestApplication(null);
        }
}

When I run this program I get output as "Array". Why does the Object constructor not run?

Nishant123
  • 1,968
  • 2
  • 26
  • 44

1 Answers1

3

Constructor overloading resolution behaves the same as method overloading resolution. When two constructors match the passed parameter, the one with the more specific argument types is chosen.

null can be assigned to both a double[] and an Object, since both are reference types, but an array is a more specific type than Object (since arrays are sub-classes of the Object class), so new TestApplication(null) triggers the TestApplication(double[] darray) constructor.

Eran
  • 387,369
  • 54
  • 702
  • 768