5

I have two methods in a class...

public void method(String var1, String var2, Object var3) {
    //do stuff
}

public void method(String var1, String var2, Object[] var3) {
    //do stuff
}

When I make the following call... obj.method("string", "string", obj) the correct method is called, however, when I try to call obj.method("string", "string", obj[]) the first incarnation of that method is called.

Is there any annotation or "hint" I can give to make sure the method I anticipate being called will be called? I know an Object[] is anObject, but I would hope that at runtime the method with Object[] would be called before Object.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
El Guapo
  • 5,581
  • 7
  • 54
  • 82
  • That shouldn't happen. Passing an `Object[]` will call the second method. – arshajii Oct 10 '13 at 13:14
  • 2
    I cant reproduce your problem. If I use reference of type `Object` I will invoke first version of method. If I would use `Object[]` reference second method will be invoked. – Pshemo Oct 10 '13 at 13:14
  • Remove the first method and pass an array of one element in the situation where you would have used the first method. – maksimov Oct 10 '13 at 13:14
  • You can always cast the third argument to `Object[]`. – Steinar Oct 10 '13 at 13:17
  • Which JVM are you using? – Mauren Oct 10 '13 at 13:23
  • Yeah... it looks like I used my SO lifeline too quickly... it IS working properly... the method call that was failing was actually trying to send in String[], not Object[], however, I still wonder why it was calling the method with Object and not Object[] (it seems to me that Object[] is more of a match than Object – El Guapo Oct 10 '13 at 13:27
  • 1
    @ElGuapo Again, I get the expected behaviour which is that the method with `Object[]` is called when passing in a String array... works for me. – Michael Berry Oct 10 '13 at 13:34
  • hmmm... who knows... what I do know is I've coded-around it for now... thanks for everyone's help – El Guapo Oct 10 '13 at 14:23

2 Answers2

8

Nope, for me this calls the second method as expected!

In the case where you want one to be called over the other, then the hint you'd give is usually a cast to the exact parameter type expected by the method (this cast will work even on null.) So using (Object)arr would force the first method to be called, but by default it will definitely call the second method (on all correct versions of the JVM anyway - contrary to popular belief, this scenario is covered explicitly in the JLS and thus is not ambiguous.)

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
0

In Java the method overload happens during compile time. That means which method is called was decided during program compilation. Note this is different from method overriding.

Alex
  • 370
  • 1
  • 6
  • 11