Put simply: I want the following code to print “sub”:
Element e = new SubElement();
print(e);
...
private static void print(Element e) {
System.out.println("e");
}
private static void print(SubElement e) {
System.out.println("sub");
}
and i dont want to change print(Element e). so nothing like
private static void print(Element e) {
if (e instanceof SubElement) {
print((SubElement) e);
} else {
System.out.println("e");
}
}
what i would like to do is
print(e.getClass().cast(e));
to automatically cast it to the real subclass and force the system to enter print(SubElement e). is this somehow possible?
Yes. You can use Visitor pattern. However it’s suitable for stablished well-defined hierarchies, because the Visitor interface you have to define needs a method for each type.