Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA Object/String method overload [duplicate]

Tags:

java

Just out of curiosity I tried this example.

public class Class1 {      public void method(Object obj){         System.out.println("Object");     }      public void method(String str){         System.out.println("String");     }      public static void main(String... arg){         new Class1().method(null);     }  } 

The output being "String". I want to know on what basis the JVM decides to invoke method taking String as argument and not Object.

like image 705
Aditya Avatar asked Jul 16 '13 06:07

Aditya


Video Answer


1 Answers

Whenever more than one overloaded methods can be applied to the argument list, the most specific method is used.

In this case either of the methods can be called when passing null, since the "null type" is assignable to both Object and to String. The method that takes String is more specific so it will be picked.

like image 96
Joni Avatar answered Sep 22 '22 13:09

Joni