Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select which overloaded version of a method to call without using a cast?

i have a question to Java Overload Methods.

Suppose i have an overload methods foo:

public static String foo(String x) {
    return "foo-String: " + x;
}

public static String foo(Object x) {
    return "foo-Object: " + x;
}

How can I implement to functions like

public static String useString() {
    return(foo("useString"));   
}
public static String useObject() {
    return(foo("useObject"));   
}

of which one uses the overloaded string method, and one the overloaded object method?

The call of the foo-Method should use an String input. (that means i do not want to work with a cast like

return(foo((Object)"useObject")); 

Maybe you can help me with this problem

EDIT:

Above, just is an example for an exercise. I am trying to understand Overloads and Dispatch better and was looking for alternative solution for calling (and selecting) an overload method.

like image 243
Aiko West Avatar asked Oct 27 '17 14:10

Aiko West


3 Answers

I guess this is a bit of cheating, but strictly speaking this doesn't use a cast on the syntax level:

public static String useObject() {
    return(foo(Object.class.cast("useObject")));   
}
like image 37
SpaceTrucker Avatar answered Nov 08 '22 09:11

SpaceTrucker


If we keep aside the motive behind this for a second and try to answer the direct question, you can create an object reference instead of using an explicit cast.

public static String useObject() {
    Object obj = "useObject";
    return foo(obj);   
}

While the end result is the same, you avoid the need to have an explicit cast with this approach.

like image 140
Chetan Kinger Avatar answered Nov 08 '22 10:11

Chetan Kinger


If you want to use the method that receive an Object, you can upcast your string to object:

public class Main {
    public static String foo(String x) {
        return "foo-String: " + x;
    }

    public static String foo(Object x) {
        return "foo-Object: " + x;
    }

    public static String useString() {
        return(foo("useString"));
    }
    public static String useObject() {
        Object x = "useObject";
        return(foo(x));
    }

    public static void main(String[] args) {
        System.out.println(Main.useObject());
    }
}

The method public static String foo(Object x) will be called

like image 1
A Monad is a Monoid Avatar answered Nov 08 '22 08:11

A Monad is a Monoid