3
package polymorphism;
/*
 * @author Rahul Tripathi
 */
public class OverLoadingTest {

    /**
     * @param args
     * @return 
     */
    static void display(String s){
        System.out.println("Print String"); 
    }

    static void display(Object s){
        System.out.println("Print Object");                 
    }

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

}

Output:

Print String

IN above program when overload same method display(String s ) and display(Object o) ,when pass null in method from main method why display(String s ) is called only. Why not called display(Object o)?

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
Rahul Tripathi
  • 545
  • 2
  • 7
  • 17

4 Answers4

2

Overloaded method is called on the basis of best/closest match. Object is the top level class, which means this will be matched at the last. So matching starts with the method taking String parameter, as string can be null so it is matched and called.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

The most non-generic method among the matching methods will be selected. i.e, null can be accepted as both Object as well as a String but Since String is also an Object, the compiler thinks that String has a higher probability of being null rather than an Object.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

Because overloadding will be happen with best closet match that is string and object is last closet one because all classes which are inherited from java.lang.object right, so that why it is happen

0

In java when multiple overloaded methods are present, java looks for the closest match first. It tries to find the following:

  1. Exact math by type

  2. Matching a superclass type

  3. Converting to a larger primitive type

  4. Converting to an autoboxed type

So in your overloaded method String class is closets sub class of object class.

VISHWANATH N P
  • 304
  • 1
  • 7
  • 11