3
 public class Test{

public static void abc(String s) {
    System.out.println("String");

}

public static void abc(Object s) {
    System.out.println("OBject");

}

 public static void main(String[] args) {
    // TODO Auto-generated method stub
    abc(null);

}}
Output-String

I am Beginner in java,I am confused about the output of the above program. Please explain me the reason of the output.

dhS
  • 3,739
  • 5
  • 26
  • 55
vinay kaushik
  • 129
  • 1
  • 8

3 Answers3

8

Early Binding (Binding most specific method at compile time).

When you overload methods, most specific method will be choosen. In your case the order of choosing is String >Object (since null can be of any reference type).

In the hierarchy, String is more specific than Object. Hence string got chosen. In fact Object is the least specific among all the java objects

Here is the JLS for the same

http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.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.

..... [rules]

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

Java compiler chooses most specific overloaded method will be selected.It is called as early binding. Here, String extends Object class hence it is more specific. You can refer official Java Language Specification

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.

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
0

The concept you have used is overloading and Object is superclass for all the classes in java. So when you provide any specific implementation (in this case its String) along with general implementation (in this case its Object) then JVM goes with specific implementation by default. If you want to try it out please replace abc(null); with abc(123);

In this case, output will be "OBject" as JVM can not find any specific implementation for integer so it goes with generalized one.

Suyash
  • 525
  • 1
  • 6
  • 10