通过使用 instanceof 设置属性在父 class 内实现多态性

achieving polymorphism within the parent class by using instanceof to set attribute

我有一个名为 AggDef 的父 class,它是某些子 classes(TermAggDef、StatAggDeff 等)的基本类型。 class 定义如下。

我在另一个 class 中有一些代码循环遍历 AggDef 对象列表并获取它们的类型。 protected Map aggregations = new HashMap();

public List<String> getAggregationTypes(){
    HashSet<String> aggTypes = new HashSet<String>();
      Iterator it = aggregations.entrySet().iterator();
      while (it.hasNext()) {
         Map.Entry pair = (Map.Entry)it.next();
         AggDef aggDef = (AggDef) pair.getValue();
         aggTypes.add(aggDef.getType());
      }
      List<String> retList = new ArrayList<String>();
      retList.addAll(aggTypes);
    return retList;
}

我的问题是,我能否在父 class 自身中实现类型属性的这种多态赋值?因为无论在哪里使用 AggDef 对象,它都会知道它是什么特定类型。我的团队成员说我应该在实际的子 classes. 中实现 setType 方法,但我不认为我在这里有错。对我的方法的准确性的任何帮助或阐述都会非常有帮助。提前谢谢你。

public abstract class AggDef implements Cloneable {
    protected String name;
    protected String term;
    protected String type;
    ...

    protected List<AggDef> subAggregations;

    public void setType(AggDef def){
        if(def instanceof TermAggDef){
            def.type = "terms";
        } 
        else if (def instanceof StatAggDef){
            def.type = "terms_stats";
        }
        else if (def instanceof RangeAggDef){
            def.type = "range";
        }
    }

    public String getType(){
        return type;
    }

    protected AggDef() {
        setType(this);
    }

    protected AggDef(String term) {
        this.term = term;
        setType(this);
    }

    protected AggDef(String name, String term) {
        this.name = name;
        this.term = term;
        setType(this);
    }


    public AggDef(String term, String order, int size, int offset, boolean isAllTerms) {
        this.term = term;
        this.size = size;
        ...

        setType(this);
    }


    public AggDef(String name, String term, String order, int size, int offset, boolean isAllTerms) {
        this.name = name;
        this.term = term;
       ...
        setType(this);
    }
 }

AggDef 只知道它自己,永远不知道它是 children。所以当它调用 setType(AggDef) 时,JVM 将引用本地定义的方法而不是 over-riden.

希望,为了帮助进一步确定主题,假设您有:

AggDef aDefObj = new AggDef();
TermAggDef taDefObj = new TermAggDef();

那么意思如下:

aDefObj instanceOf AggDef // true 
aDefObj instanceOf TermAggDef  // false 
taDefObj instanceOf AggDef // true
taDefObj instanceOf TermAggDef // true

查看 Oracle 的 Inheritance 文档,特别是 Casting。