Say, there is a following example:
class Super {
public int i = 3;
public void m(Object o) {
System.out.println("Object " + i);
}
public void m(String o) {
System.out.println("String " + i);
}
}
public class Sub extends Super {
public Sub() {
i = 5;
}
public static void main(String[] args) {
Super s = new Sub();
Object o = "";
s.m(o);
s.m("");
}
}
The result of this code is:
Object 5
String 5
But I thought it would be:
String 5
String 5
Don’t quotes set String as this object’s type? There are definitely some cases of casting to String with a help of quotes, so I’m a little confused about this basic example. Thanks in advance.
The type of the method is determined in compile time, and not in run time. The dynamic dispatch exists only for the “parameter”
this– there is no dynamic dispatch for parameters in static typing languages such as java.The compiler “choses” which method should be invoked, and since
ois of typeObject– it chosesm(Object)– it has no way to know that the dynamic type ofois actually aString.If you are interested – a common way to overcome this issue in some cases is using the visitor design pattern.
In your specific case, in order to “force” the activation of
m(String)you should usem(o.toString())