Consider the following:
public class GenericTest {
static void print(int x) {
System.out.println("Int: " + x);
}
static void print(String x) {
System.out.println("String: " + x);
}
static void print(Object x) {
System.out.println("Object: " + x);
}
static <T> void printWithClass(T t) {
print(t);
}
public static void main(String argsp[]) {
printWithClass("abc");
}
}
It prints Object: abc.
Why doesn’t it print String: abc?
Java supports method overriding (dynamic type binding), but not what you are trying to achieve (overloading is static polymorphism and not dynamic).
In order to achieve what you want to achieve in Java, you need double dispatch.
Visitor Pattern should be your friend here.
I have written you a code sample.