2

Here is the code:

public class OverloadingByObject {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Object object = null;
        new OverloadingByObject().SayHi(null);
        new OverloadingByObject().SayHi(object);
    }

    public void SayHi(String str) {

        System.out.println("String called");
    }

    public void SayHi(Object obj) {

        System.out.println("Object called");
    }
}

When I am passing null it should call the method of Object. What is the reason it is calling method of String ?

romfret
  • 391
  • 2
  • 11
Kishan Bheemajiyani
  • 3,429
  • 5
  • 34
  • 68

1 Answers1

7

null can be assigned to any reference type. When deciding which overloaded version of a method will be called, the method with the most specific arguments is chosen. String is more specific than Object (since String is a sub-class of Object). Therefore SayHi(String str) is called for a null argument.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • So u are sure that it will prefer first Sub-class metod. – Kishan Bheemajiyani May 22 '15 at 13:40
  • @Krishna It will prefer the method with the most specific argument types. However, if you add another method, such as `SayHi(Integer i)`, calling `SayHi(null)` won't pass compilation, since neither Integer nor String is more specific than the other. – Eran May 22 '15 at 13:43
  • Running this example I am getting "Object called" twice. – user987339 May 22 '15 at 14:05
  • @user987339 strange, I'm getting `String called Object called`, which is the expected behavior. – Eran May 22 '15 at 14:08
  • can you paste it on ideone? – user987339 May 22 '15 at 14:08
  • @user987339 It looks like you ran this code as Groovy code. Perhaps Groovy behaves differently. When changing the language to Java and changing the class name to Main, you get the result I got. http://ideone.com/aoLYTL – Eran May 22 '15 at 14:14
  • yes, groovy works a bit different. I apologise. – user987339 May 22 '15 at 14:21