10

I am not able to understand the output of the following program.

public class Confusing {

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

    private Confusing(double[] dArray) {
        System.out.println("double array");
    }

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

The correct output is "double array". WHy was this constructor chosen as more specific than the other when both can accept null?

slim
  • 40,215
  • 13
  • 94
  • 127
user1614482
  • 101
  • 3
  • possible duplicate of [Which overload will get selected for null in Java?](http://stackoverflow.com/questions/1545501/which-overload-will-get-selected-for-null-in-java) – João Silva Aug 21 '12 at 14:41

2 Answers2

18

Even though both constructors can accept null, double[] inherits from java.lang.Object, and is therefore more specific.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • @downvoter would you care to elaborate on what you think is wrong with the answer? – Sergey Kalinichenko Aug 21 '12 at 14:53
  • 1
    Maybe because of [this](http://en.wikipedia.org/wiki/Resentment) (disclaimer: wasn't me) – David Aug 21 '12 at 14:59
  • I read this in Liskov's book "A method m1 is more specific than another method m2 if any legal call of m1 would also be a legal call of m2 if more conversions were done". This mean if there is a method comp(int) and comp(long), passing an int param will go to comp(int) (which is m1 above) as it could also go to comp(long) (which is m2 above) with conversion. But a vice versa does not hold as a comp cannot be passed to m1. However, how can you apply this logic to a null param in my original question - it can be applied to both double[] and Object without conversion?? – user1614482 Aug 21 '12 at 15:21
  • 1
    @user1614482 `int` and `long` are primitives, with conversion rules defined for them; unlike `Object` and `double[]`, neither one is a subclass of the other. When overloads use a single parameter related as base-subclass, the subclass wins when `null` is passed. – Sergey Kalinichenko Aug 21 '12 at 15:25
1

The challenge of compiling dynamically typed languages is how to implement a runtime system that can choose the most appropriate implementation of a method or function — after the program has been compiled. Treating all variables as objects of Object type would not work efficiently.

Hence, choosing the specific one over Object.

Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108