java - 实现一个接口(interface),该接口(interface)有一个返回接口(interface)的方法,但收到未实现的错误

标签 java interface abstract

我正在为人工智能类(class)做一些事情,但我似乎有一些项目结构问题。我知道这在 Python 中更容易完成,但我已经这样做了,而且我正在 Java 中这样做,因为我有时间消磨。

我的类(class)设置如下:

  1. 我有 3 个接口(interface):ProblemInterface , ActionInterface , StateInterface .
  2. 我有一个 Search 类,它调用 ProblemInterface 中定义的方法。因此保留 ArrayListProblemInterface
  3. 我有一个ProblemQ1 (尝试)实现 ProblemInterface 的类。其他类ActionQ1StateQ1实现各自的接口(interface)。
    • class ProblemQ1 implements ProblemInterface
    • class ActionQ1 implements ActionInterface
    • class StateQ1 implements StateInterface
  4. ProblemInterface定义了一个名为 actions() 的方法接受 StateInterface参数并返回 ArrayList<ActionInterface> 。所以,像这样:
    • ArrayList<ActionInterface> actions(StateInterface state);
  5. 因此,我的ProblemQ1类试图定义 actions()通过让它采取 StateQ1参数并让它返回 ArrayListActionQ1的。
    • public ArrayList<ActionQ1> actions(StateQ1 state)
  6. ProblemQ1类不能是抽象的,因为我必须为我想要解决的每个问题实例化它。
  7. 我必须做其他ProblemQN , StateQNActionQN稍后的类,它们实现各自的接口(interface)。

但是,我收到一个编译器错误,告诉我我的 ProblemQ1类必须是抽象的或实现 ProblemInterface方法。从我所看到的,它遵循接口(interface)的规则,我不明白为什么它不处理定义 actions()ProblemQ1定义接口(interface)。

最佳答案

From what I'm seeing, it follows the rules of the interface, and I can't see why it wouldn't treat defining actions() in ProblemQ1 as defining the interface.

否,您更改了 ProblemQ1 中方法的参数类型:

public ArrayList<ActionQ1> actions(StateQ1 state)

虽然接口(interface)定义了如下方法:

ArrayList<ActionInterface> actions(StateInterface state);

这意味着您重载而不是覆盖该方法。
使用 @Override 注释该方法您会看到编译器不会将其视为覆盖。
另请注意,重写的返回类型也不兼容。
ArrayList<ActionQ1>不是 ArrayList<ActionInterface> 的子类.
但是ArrayList<ActionQ1>ArrayList<? extends ActionInterface> 的子类。

要解决您的问题,您可以在界面中引入泛型:

public interface ProblemInterface<T extends StateInterface, U extends ActionInterface>{   
    ArrayList<U> actions(T state);
}

实现可能是这样的:

public class ProblemQ1 implements ProblemInterface<StateQ1, ActionQ1>{

    public ArrayList<ActionQ1> actions(StateQ1 state){
      // ...
    }
}

关于java - 实现一个接口(interface),该接口(interface)有一个返回接口(interface)的方法,但收到未实现的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53143172/

相关文章:

struct - Golang 在结构之间切换

JavaFX - 保存/加载 - 形状/布局

java - 无法从 Windows 连接到远程 HDFS

java - Android不幸的应用程序已停止?

java - 安卓(Java): DRYer approach using interfaces and less duplication

java - 静态/抽象冲突

java - 如何从文本字段打开任何文件?

c# - .NET 运行时序列化

java - 用抽象方法覆盖默认接口(interface)方法

c# - 如何解决我的游戏中继承2个抽象类的问题?