Skip to content
Advertisement

Method Overloading – Java

Actual Question: If it calls (1) then how can I make it so that it calls (2) ?

I have following methods signature

public void myMethod(String myStr, MyClass myClass) {...} // (1)

public void myMethod(Object... objects) {...} // (2)

Somewhere I make a call like

myMethod(new String("name"), new MyClass());

Which overloaded method will be called ? If it calls (1) then how can I make it so that it calls (2) ?

Advertisement

Answer

It will call (1) because the method resolution algorithm gives priority to methods that do not use varargs.

To force it to use (2) you can pass an array or cast the first parameter to Object:

myMethod(new Object[] { "name", new MyClass() });
//or
myMethod((Object) "name", new MyClass());
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement