Java 当实例可能具有不同的数据类型时,如何返回实例的正确数据类型?

Java 当实例可能具有不同的数据类型时,如何返回实例的正确数据类型?,java,function,types,instance,Java,Function,Types,Instance,我在模块A-2中有这个代码 PROCEDURE Prune(typeExp: TypeExp): TypeExp; BEGIN CASE typeExp.^class OF | VarType: IF typeExp^.instance = NIL THEN RETURN typeExp; ELSE typ

我在模块A-2中有这个代码

PROCEDURE Prune(typeExp: TypeExp): TypeExp;
    BEGIN
        CASE typeExp.^class OF
            | VarType:
                IF typeExp^.instance = NIL THEN
                    RETURN typeExp;
                ELSE
                    typeExp^.instance = Prune(typeExp^.instance);
                    RETURN typeExp^.instance;
                END;
            | OperType: RETURN typeExp;
            END;
END Prune;
当我试图将这段代码转换成java时,我遇到了几个问题。我可以创建一个实例,判断它的实例是否为null,然后选择返回什么。但我真的不知道如何处理案例2,即该实例可能是一个新的Opentype();因为在这种情况下只能返回一个值

public TypeExp Prune(TypeExp typeExp){
    TypeExp r = new VarType();
    if (r.instance == null) {
        return r;
    }
    else {
        r.instance = Prune(r.instance);
        return r.instance;
    }
}

第二个问题是我不认为我可以在函数本身内部调用函数Prune(),那么我能做什么呢?提前谢谢。

我真的不知道Modula-2,但可能是这样的:

public TypeExp Prune(TypeExp typeExp) {
    if (typeExp instanceof VarType) {
        if (typeExp.instance == null) {
            return typeExp;
        }
        else {
            typeExp.instance = Prune(typeExp.instance);
            return typeExp.instance;
        }
    } else if (typeExp instanceof OperType) {
        return typeExp;
    }
    //if typeExp is not an instance of VarType or OperType
    return null;
}

Modula代码不会在所有代码路径中返回。这在Java中是不可能的。在这些情况下,我插入了returnnull。但对于你的应用程序来说,这可能是错误的

我真的不知道模A-2,但它可能是这样的:

public TypeExp Prune(TypeExp typeExp) {
    if (typeExp instanceof VarType) {
        if (typeExp.instance == null) {
            return typeExp;
        }
        else {
            typeExp.instance = Prune(typeExp.instance);
            return typeExp.instance;
        }
    } else if (typeExp instanceof OperType) {
        return typeExp;
    }
    //if typeExp is not an instance of VarType or OperType
    return null;
}

Modula代码不会在所有代码路径中返回。这在Java中是不可能的。在这些情况下,我插入了returnnull。但对于你的应用程序来说,这可能是错误的

下面的示例与您的func不同,但我认为您可以根据需要进行修改。它将返回类型隐藏在Type class=>后面,您可以返回两个类的对象

主要

类型

第一型

package com.type;

public class FirstType extends Type {
}
第二类

package com.type;

public class SecondType extends Type {
}

下面的示例与您的func不同,但我认为您可以根据需要进行修改。它将返回类型隐藏在Type class=>后面,您可以返回两个类的对象

主要

类型

第一型

package com.type;

public class FirstType extends Type {
}
第二类

package com.type;

public class SecondType extends Type {
}

对不起,我忘了在原始模块代码中添加return。我能问一下为什么在第7行有一个新的Pre Prune吗?哦,sry,我以为这是一个新的对象。但这是一个递归调用。我在回答中更改了它。对不起,我忘了在原来的Modula代码中添加return。我能问一下为什么在第7行有一个新的Pre Prune吗?哦,sry,我以为这是一个新的对象。但这是一个递归调用。我在回答中改变了它。