You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过继承实现同一函数返回不同类型,无需instanceof判断节点值?

实现方案

核心思路是利用Java多态特性,将值比较的逻辑下沉到各个子类实现,父类只定义统一的抽象比较接口,外层isExists方法完全不需要感知具体子类类型,自然不需要在该方法内使用instanceof做类型判断。

第一步:重构父类Node

将原有的普通Node类修改为抽象类,定义统一的抽象比较方法和取值方法:

public abstract class Node {
    // 抽象方法:由子类实现当前节点与目标节点的值是否相等
    public abstract boolean valueEquals(Node other);
    // 统一获取节点存储的值,可根据业务需要选择是否定义
    public abstract Object getValue();
}

第二步:各子类实现抽象方法

IntegerNode子类实现

public class IntegerNode extends Node {
    private Integer integerNode;

    IntegerNode(int number){
        this.integerNode = number;
    }

    @Override
    public Integer getValue(){
        return integerNode;
    }

    @Override
    public boolean valueEquals(Node other) {
        // 非同类节点直接返回不相等
        if (!(other instanceof IntegerNode)) {
            return false;
        }
        // 同类节点比较内部存储的值
        return this.integerNode.equals(((IntegerNode) other).integerNode);
    }
}

CharNode子类实现

public class CharNode extends Node {
    private Character charNode;

    CharNode(char digit){
        this.charNode = digit;
    }
    
    @Override
    public Character getValue(){
        return charNode;
    }

    @Override
    public boolean valueEquals(Node other) {
        if (!(other instanceof CharNode)) {
            return false;
        }
        return this.charNode.equals(((CharNode) other).charNode);
    }
}

注:此处的instanceof仅在子类内部使用,是子类自身的类型校验逻辑,符合面向对象开闭原则,后续新增其他Node子类时不需要修改外层isExists的代码。

第三步:实现isExists方法

外层逻辑直接调用统一的valueEquals方法即可完成判断,不需要做任何类型检查:

boolean isExists(List<Node> list, Node value){
    for (Node node : list) {
        if (node.valueEquals(value)) {
            return true;
        }
    }
    return false;
}

可选简化方案

如果直接重写各子类的equals和hashCode方法,isExists可以进一步简化为一行代码:

boolean isExists(List<Node> list, Node value){
    return list.contains(value);
}

内容的提问来源于stack exchange,提问作者John Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:36:06