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(st开发者_如何学运维yle.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.
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.
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.
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.
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.
精彩评论