How to choose which overloaded version of the method to call without using translation?

I have a question for Java overload methods.

Suppose I have foo overload methods:

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

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

How can I implement features like

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

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

The foo-Method call must use String input. (this means that I do not want to work with cast, for example

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

Perhaps you can help me with this problem.

EDIT:

The above is just an example of an exercise. I am trying to better understand Overloads and the Dispatcher and have been looking for an alternative solution to invoke (and select) the overload method.

+6
3

, .

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

, .

+3

, , , , :

public static String useObject() {
    return(foo(Object.class.cast("useObject")));   
}
+1

If you want to use a method that receives an object, you can raise your string to an 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

+1
source

All Articles