gpt4 book ai didi

java - 如何从变量为父类(super class)的 "for"内的子类执行方法?

转载 作者:行者123 更新时间:2023-12-01 17:16:40 26 4
gpt4 key购买 nike

我有一个名为 Agent 的类:

abstract public class Agent {
// this class doesn't has the method "method_A"
}

还有一个 AgentHistoric 类:

public class AgentHistoric extends Agent{
public void method_A(){
code
}
}

我还有类 RandomAgent、AgentAlways0 等,它们都扩展了抽象类 Agent,但只有 AgentHistoric 具有方法“method_A”。

假设我创建了 AgentHistoric 的 objetcs、RandomAgent 的 objetcs 等,并将它们添加到名为agents 的 ArrayList 中。

在另一个类(class)中,我有以下代码:

for (Agent ag: this.agents ){
ag.update(); // all Agent's subclasses have this method
if (ag.returntype() == AgentHistoric){ // I know there's a more elegant way, but OK
method_A() } // error!
}

如何在此循环中执行 AgentHistoric 的独占方法?

最佳答案

使用 instanceof 运算符确定 ag 是否为 AgentHistoric。如果是这样,请将 ag 转换为 AgentHistoric,然后调用 method_A

关于java - 如何从变量为父类(super class)的 "for"内的子类执行方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21613231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com