Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

how can I invoke a method on a subclass based on the runtime type?

807589Sep 4 2008 — edited Oct 23 2008
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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 20 2008
Added on Sep 4 2008
14 comments
208 views