0

I want to know whether this is a valid overloading :

public class OverLoadingTest{

     private void callFunction(Object object){
              System.out.println("Printing Object");
     }

     private void callFunction(String string){
              System.out.println("Printing String");
     }

}

Further more, since someone asked me this question. If I do like this,

OverLoadingTest test = new OverLoadingTest();
test.callFunction(null);

what will be printed ?

Of course my opinion is that it isn't valid overloading at all. So no question of the second part.

Please tell me about this with some explanation.

Ankit
  • 4,426
  • 7
  • 45
  • 62

2 Answers2

3

The method with the least generic argument is called. So, in your case, it will be method accepting String

Note : If 2 classes are at the same level, then you will get an ambiguous call exception. For example if one method took String and another took Exception.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • could you please explain the last line `if one method took String and another took Exception` – Shailesh Aswal Dec 26 '14 at 08:45
  • @Shail016 - See, If 2 classes are at *different* level in the *class hierarchy*, then the *lower* level class will be chosen. So, if the arguments were `IOException` and `Exception`, `IOException` will be printed since it is a *subclass* of `Exception` (the *least generic*). The same concept applies to `String` and `Object`. Since `String` is a *subclass* of `Object`. Now, if you have `IOException` and `InterruptedException`, then the call will be *ambiguous* since both classes are at the *same level*. Got it? – TheLostMind Dec 26 '14 at 08:50
  • Also, the classes *must* have a relation between them. `FileNotFoundException` and `String` will give *compile-time* error – TheLostMind Dec 26 '14 at 08:55
2
If more than one member method is both accessible and applicable to a method 
invocation, it is necessary to choose one to provide the descriptor for 
the run-time method dispatch.
The Java programming language uses the rule that the most specific method is chosen.

See more details in JSL 15.12.2.5

  • In your case, String method will be invoked, if argument is String or null and for other argument's types Object method will be invoked.
  • In your example, if you define one more method with argument type that is not String (e.g Integer), can't compile the source as it is ambiguous to be invoked between the methods with String and Integer as they are same level.
Wundwin Born
  • 3,467
  • 19
  • 37