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

标签 java inheritance polymorphism subclass

我有一个名为 DataItem 的父类(super class),它有多个 child , child 也有 child 。我动态设置了对象类型,但最终类型引用是 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();
}

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

DataItem dataItem = getDataItemUponType(parent,element);

然后我想从 DataItem 的子类型调用。我该怎么做?

注意:我需要使用 DataItem,所以将其抽象化对我来说不起作用。

最佳答案

您正试图打破抽象的想法:您应该对 DataItem 没意见。它应该具有您实际想要调用的所有方法。这是主要思想:

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

尝试重新考虑您的设计。

关于java - 如何从父引用调用子方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6198251/

相关文章:

polymorphism - SML中的 'a and ''a有什么区别?

java - SSL 与 javamail 不工作

java - iText 5 getDefaultCell().setBorder(PdfPCell.NO_BORDER) 无效

java - 渐进式 HMACSHA256 的 C# 等效项是什么?

c# - oop 检查返回类型是父类还是子类

Javascript继承思想(二)

java - 如何在java中使用hashmap删除重复的数组元素

java - 具有父类(super class)引用变量的 Java 子类对象中的方法重载/覆盖

java - 有没有办法向下转型 GWT AutoBean?

namespaces - 具有多态关系的命名空间 Laravel 5