我正在为人工智能类(class)做一些事情,但我似乎有一些项目结构问题。我知道这在 Python 中更容易完成,但我已经这样做了,而且我正在 Java 中这样做,因为我有时间消磨。
我的类(class)设置如下:
- 我有 3 个接口(interface):
ProblemInterface
,ActionInterface
,StateInterface
. - 我有一个 Search 类,它调用
ProblemInterface
中定义的方法。因此保留ArrayList
的ProblemInterface
- 我有一个
ProblemQ1
(尝试)实现ProblemInterface
的类。其他类ActionQ1
和StateQ1
实现各自的接口(interface)。-
class ProblemQ1 implements ProblemInterface
-
class ActionQ1 implements ActionInterface
-
class StateQ1 implements StateInterface
-
ProblemInterface
定义了一个名为actions()
的方法接受StateInterface
参数并返回ArrayList<ActionInterface>
。所以,像这样:-
ArrayList<ActionInterface> actions(StateInterface state);
-
- 因此,我的
ProblemQ1
类试图定义actions()
通过让它采取StateQ1
参数并让它返回ArrayList
的ActionQ1
的。-
public ArrayList<ActionQ1> actions(StateQ1 state)
-
ProblemQ1
类不能是抽象的,因为我必须为我想要解决的每个问题实例化它。- 我必须做其他
ProblemQN
,StateQN
和ActionQN
稍后的类,它们实现各自的接口(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/