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 ?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

So u are sure that it will prefer first Sub-class metod.
@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.
Running this example I am getting "Object called" twice.
@user987339 strange, I'm getting String called Object called, which is the expected behavior.
can you paste it on ideone?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.