2

Let us say I have following overloaded functions

public class Test {

    public static void funOne(String s){
        System.out.print("String function");
    }

    public static void funOne(Object o){
        System.out.print("Object function");
    }

    public static void main(String[] args) {            
        funOne(null);
    }
}

Why would funOne(null) call the method with String argument signature? what is the precedence for overloading here?

Puru--
  • 1,111
  • 12
  • 27
  • 2
    Java isn't C++. You shouldn't really try to compare the two, especially when discussing function overloading. – PaulMcKenzie Apr 05 '14 at 22:43
  • @PaulMcKenzie Agreed , I am guessing it uses class hierarchy to determine the precedence , if I add another funOne(Integer) code does not compile. I am taking out "Is this behavior same in C++?" – Puru-- Apr 05 '14 at 22:44
  • possible duplicate of [Method Overloading for NULL parameter](http://stackoverflow.com/questions/5229809/method-overloading-for-null-parameter) – merlin2011 Apr 05 '14 at 22:50

2 Answers2

3

The class that is lower in the class hierarchy will have precedence in this case. In other words the more specific class type, which would be String in this case because String extends Object technically.

If you have the following

public class A {
    ...
}

public class B extends A {
    ...
}

Then when you define overloading methods like the following:

public void test(A object) {
    ...
}

public void test(B object) {
    ...
}

Then calling test(null) will call the second method because B is lower in the class hierarchy.

Tamby Kojak
  • 2,129
  • 1
  • 14
  • 25
1

Your question is more fully answered here with references.

Also, you can force a particular method to be called by doing this:

    funOne((Object) null);
Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • Thanks , I could make guess but I was searching for [JLS Reference](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5) , thank you for your answer – Puru-- Apr 05 '14 at 23:00