ikbal
ikbal

Reputation: 1894

how to call child method from parent reference?

I have a superclass called DataItem and it has multiple children and the children have children too. I dynamically set the object type but in the end the type reference is DataItem. Here is the code I use to determine the class type:

private DataItem getDataItemUponType(DataSection parent,Element el) {
    String style = getItemStyle(parent,el);
    if(style!=null) {
        if(style.equals("DUZ")) {
            return new DataItemPlain();
        } else if(style.equals("TVY")) {
            return new DataItemPaired();
        } else if(style.equals("TVA")) {
            return new DataItem();
        } else if(style.equals("FRM")) {
            return new DataItemForm();
        } else if(style.equals("IMG")) {
            return new DataItemImage();
        } else if(style.equals("CLN")) {
            return new DataItemCalendar();
        } else if(style.equals("BTN")) {
            return new DataItemButton();
        } else if(style.equals("ALT")) {
            return new DataItemSubRibbon();
        }
    } else {    
        // At least return a DataItem.
        return new DataItem();
    }
    return new DataItem();
}

Then I use this to set my object:

DataItem dataItem = getDataItemUponType(parent,element);

Then I want to call from a subtype of DataItem. How do I do that?

Note: I need to use DataItem so making it abstract wouldn't work for me.

Upvotes: 1

Views: 5768

Answers (4)

amukhachov
amukhachov

Reputation: 5900

You can check if you DataItem object is instanceof some DataItem child class. After that you just need to cast this object to that class, so you'll be able to call its methods.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533880

You can call the method on DataItem which you override for sub-classes. The method for the actual type is the one which is called. The is a standard polymorphism technique.

Upvotes: 0

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

You might want to use the instanceof keyword like so:

if (o instanceof DataItemRibbon)
  ((DataItemRibbon)o).doSomething();

EDIT
I agree with Vladimir Ivanov that what I've written works, but is an indication of bad design. You should rework your object hierarchy like Vladimir suggests.

Upvotes: 2

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43108

You're trying to break the idea of the abstraction: you should be fine with DataItem. It should have all the methods you would actually want to invoke. That's the main idea:

Have an interface to describe the communication and hide the implementation.

Try to reconsider your design.

Upvotes: 5

Related Questions