Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null value considered as Object or Array

Tags:

java

arrays

null

public class Test
 {

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

    public Test(int[] o) {
        System.out.println("array");
    }

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

Output :

array

Can somebody please explain me the reason behind this?

like image 356
Rajeev Akotkar Avatar asked Jan 10 '23 09:01

Rajeev Akotkar


1 Answers

The rule is: the more specific method will be called. In this case, it's the method receiving a int[] which is more specific than the one receiving a java.lang.Object parameter.

Here's a link to Java's official documentation referencing to this case. Take a look at section 15.2.2. Quoting an interesting part (section 15.2.2.5):

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

An another one:

It is possible that no method is the most specific, because there are two or more methods that are maximally specific. In this case:

If all the maximally specific methods have override-equivalent (§8.4.2) signatures, then: If exactly one of the maximally specific methods is not declared abstract, it is the most specific method. Otherwise, if all the maximally specific methods are declared abstract, and the signatures of all of the maximally specific methods have the same erasure (§4.6), then the most specific method is chosen arbitrarily among the subset of the maximally specific methods that have the most specific return type. However, the most specific method is considered to throw a checked exception if and only if that exception or its erasure is declared in the throws clauses of each of the maximally specific methods. Otherwise, we say that the method invocation is ambiguous, and a compile-time error occurs.

like image 66
Pablo Santa Cruz Avatar answered Jan 22 '23 07:01

Pablo Santa Cruz