0

I have a dummy program in java given below-

public class DummyTest {
    public static void main(String[] args) {
        hungry(null);
    }

     public static void hungry(Object o){
        System.out.println("object");
    }

    public static void hungry(String s){
        System.out.println("string");
    }
}

this program returns prints string. please tell me the concept that why it prints string and not object.

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70

1 Answers1

4

This is how method overloading works. When the parameter of one candidate is more specific than the parameter of the other (as String is more specific than Object), the method with the more specific parameter is chosen.

Note that if you add a 3rd hungry method with a parameter of reference type unrelated to String (for example Integer), the code won't pass compilation since the compiler won't have a preference between hungry(String) and hungry(Integer).

Eran
  • 387,369
  • 54
  • 702
  • 768