I learned that I can use the real type of a Object to define which Method is used, such like this:
[...]
Object foo = new String("hello");
[...]
bla(foo);
void bla(String x){
}
void bla(Integer x){
}
Now it should take the bla(String x) method, but instead I get compiler error. I know why: because the type of foo is currently Object. I’m not sure if I do it currently right, but I understood it that way, that Java will choose the method by the real type (or specific type), so if I downcast it to Object, it will choose the String instead, if no Object Method is specified.
Or is the only way to determinate the type by if(foo instanceof xxx) in a method void bla(Object x)?
P.S.: dont get me wrong on this: I dont mean that I can overload methods, I mean that I want to choose the method based on the real type (not on the defined one)!
Right. Which method is to be called at runtime, is chosen at compile-time, and the compiler can’t (in general) tell which type
foowill have in runtime.You can’t “downcast to Object”. You can downcast to a
Stringthough. And that’s right, if you doit will invoke the
blathat takes aStringas argument (and throw aClassCastExceptioniffoois not aString).This is usually referred to as double or multiple dispatch, and is a feature not supported in Java.
Implement the visitor pattern if you really need this.
Btw, what you refer to as “defined type” and “real type” are usually referred to as static type and runtime type respectively. That is,
Objectis the static type offoo, whileStringis it’s runtime type.