Hi all,
I have defined a base class OrderDetail, and 2 subclasses which extend it: OrderDetailSingleReservation and OrderDetailMonthReservation. Furthermore, I have a method:
public Order order_generate(OrderDetail orderDetail) {
if (orderDetail instanceof OrderDetailSingleReservation) {
return order_generate((OrderDetailSingleReservation) orderDetail);
} else if (orderDetail instanceof OrderDetailMonthReservation) {
return order_generate((OrderDetailMonthReservation) orderDetail);
} else {
Misc.alert("orderAndInvoice_Generate(GENERIC): unsupported type.");
return null;
}
}
The type of this method's parameter is OrderDetail, as you can see. (This particular method only serves as a kind of dispatcher and is therefore not very interesting in itself, but the same pattern using 'instanceof' occurs in a codebase I am working on several times, and I would like to factor it out if possible.)
My question: it seems that the invocation of order_generate() from within this method requires an explicit downcast to one of the two subclasses. If not, java invokes the method on the superclass. But at runtime, the JVM knows what type of object it is dealing with, right? So is there no way to do this without the explicit downcast?
A similar problem occurs when trying to invoke a method on an object whose type is one of the subclasses; the method on superclass is called, instead of the one in the appropriate subclass that overrides it.
Any help would be greatly appreciated!
Thanks,
Erik