Object vs String Method

java

Solution

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

Problem

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); } } ```

Original source

Related problems