我正在用 Java 制作一个简单的游戏,我有这个疑问。
假设每个游戏角色都有一个界面
public interface Entity{
Vector2 getPosition();
/* More methods...*/
}
然后我想创建一个名为 Automata 的接口(interface),由每个使用 AI 东西的类实现(这可能是 Entity 的特例,但由于可重用性,我认为它是分开的)
public interface Automata{
Vector2 getPosition(); // The AI stuff needs to know this
/* More methods needed for AI (some may also be the same as Entity)... */
}
我认为这促进了模块化,因为每个接口(interface)都描述了它的方法而不用担心其他接口(interface)的存在,但是当我写这个的时候我觉得我在重复自己,所以有这两个(或可能更多)接口(interface)用同样的方法有什么不好的?
最佳答案
如果两个接口(interface)之间有一些共同点,那么也许您可以定义一个父接口(interface),然后 Entity
和 Automata
可以扩展它。
让我在下面举例说明:
interface AI {
Vector2 getPosition();
}
interface Entity extends AI { }
interface Automata extends AI { }
这样,作为 AI 一部分的任何其他接口(interface)都不需要显式添加其他方法,而只需扩展 AI
关于java - 两个或多个接口(interface)可以有相同的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795580/