Null value treated as an object or array

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 someone explain the reason for this to me?

+4
source share
5 answers

Rule: a more specific method will be called . In this case, it takes a method int[]that is more specific than the one that takes the parameter java.lang.Object.

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

- , . Java , .

, , , , , , .

:

, , , . :

- (§8.4.2), : , . , (§4.6), , . , . , , .

+7

. Object one, :

new goFuncTest((Object) null);
+1

, / . , , , . .

2 , - ambiguous method call, .

public class Sample {
void someMethod(Object o) {
    System.out.println("object");
}

void someMethod(String s) {
    System.out.println("String");
}

void someMethod(int[] o) {
    System.out.println("int[]");
}

public static void main(String[] args) {
    new Sample().someMethod(null); // error ambiguous call both array and String are direct children of Object
}

-2: , .

public class Sample {
void someMethod(Object o) {
    System.out.println("object");
}

void someMethod(OutputStream os) {
    System.out.println("OutputStream");
}

void someMethod(FileOutputStream fos) {
    System.out.println("FileOutputStream");
}

public static void main(String[] args) {
    new Sample().someMethod(null);
}

}

O/P: FileOutputStream

FileOutputStream OutputStream, Object (FileOutputStream OutputStream Object). , Object --> OutputStream --> FileOutputStream .

+1

The Thumb Rule is the first in a method call. Since Object is the parent of all, and since a NULL value can be assigned to an instance type variable of any type, it will first correspond to any java type (which, of course, is a descendant of the object), and then to the super-parent, i.e. object.

0
source

An up gradation from Null to Array is preferable to pouring it in Object. The object is on top of the hierarchy, and the array is closer to Null.

This is similar to byte gradation to int.

0
source

All Articles