Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object vs String Method [duplicate]

Tags:

java

Possible Duplicate:
Overloaded method selection based on the parameter’s real type
How is an overloaded method choosen when a parameter is the literal null value?

When I execute the code below, I get the following output:

Method with String argument Called ..."

Why?

public class StringObjectPOC {

    public static void test(Object o)   {
        System.out.println("Method with Object argument Called ...");
    }
    public static void test(String str){
        System.out.println("Method with String argument Called ...");
    }
    public static void main(String[] args) {
        StringObjectPOC.test(null);
    }
}
like image 207
Alpesh Gediya Avatar asked Oct 30 '12 05:10

Alpesh Gediya


4 Answers

The null in the call matches both the test() signatures. You have to cast the null to ensure it calls one or the other.

like image 195
Zagrev Avatar answered Sep 20 '22 13:09

Zagrev


A similar example is from Java Puzzles if I recall correctly.

null can be of String type or Object type. But the JVM will always choose a more accurate method.

In this case, String is more accurate then Object. (a String is an Object, but an Object might not be a String).

It is not a good habit to write code like this. Try to cast parameters to match your desired method, like

public class StringObjectPOC {

    public static void test(Object o)   {
        System.out.println("Method with Object argument Called ...");
    }
    public static void test(String str){
        System.out.println("Method with String argument Called ...");
    }
    public static void main(String[] args) {
        StringObjectPOC.test((Object)null);
    }
}
like image 40
onemach Avatar answered Sep 21 '22 13:09

onemach


I tried this:

Test2.class

public class Test2{}

Test3.class

public class Test3 extends Test2{

}

Test.class

public class Test{

public static void print(Object obj){
    System.out.println("Object");
}

public static void print(Test2 obj){
    System.out.println("test 2");
}

public static void print(Test3 obj){
    System.out.println("Test 3");
}


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

}

it printed out Test 3

Just like in your scenario, this means that if a method is overloaded (and when null is passed), it recognizes the method which has the child-most parameter.

Object->Test->Test2

or in your case:

Object->String
like image 32
Russell Gutierrez Avatar answered Sep 21 '22 13:09

Russell Gutierrez


Java tries to find the most specific method possible to call. String is a subclass of object, so Java will defer to the String method whenever it can. null is a perfectly acceptable value for either an Object or a String, but since a String is more specific than an Object, Java defers to the String method because it is more precise.

like image 35
ApproachingDarknessFish Avatar answered Sep 21 '22 13:09

ApproachingDarknessFish