如何从父引用调用子方法?

ikb*_*bal 1 java polymorphism inheritance subclass

我有一个超级课程DataItem,它有多个孩子,孩子也有孩子.我动态设置了对象类型,但最后是类型引用DataItem.这是我用来确定类类型的代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

然后我用它来设置我的对象:

DataItem dataItem = getDataItemUponType(parent,element);

然后我想从一个子类型调用DataItem.我怎么做?

注意:我需要使用,DataItem所以使它抽象不适合我.

Vla*_*nov 5

你试图打破抽象的想法:你应该没关系DataItem.它应该具有您实际想要调用的所有方法.这是主要的想法:

Have an interface to describe the communication and hide the implementation.
Run Code Online (Sandbox Code Playgroud)

尝试重新考虑您的设计.