1

I am creating a mod for the game Minecraft, which has an interface to implement in-game commands. I need the mod to implement that interface, but override one of its methods with a non-compatible method (different return type). But I need to prevent a situation where other classes that implement that interface will not work or not be recognized by the game.

I think this would require overriding the interface with a new interface that is the same as the original, but with an overloaded version of that method to support the mod's needs. Is this possible (or is there another way I can accomplish this?)

4

3 回答 3

2

考虑接口的一种方法是作为合同。
实现类必须严格遵守这个契约。这意味着方法签名(包括返回值和参数)必须完全匹配。
接口的全部意义在于在不严格了解实现的情况下定义交互。

如果您希望实现的交互不同,那么您可能正在尝试以非预期的方式使用某些东西。

即使可以对接口进行子类化,它也会很快变得混乱。创建一个新接口可能最符合您的利益(所有其他方法都相同)。由于它无法与使用接口 A 的类进行比较,因此您可以通过将其完全分离来省去麻烦。

于 2016-01-05T20:02:25.027 回答
1

Mojang/forge 团队提供的接口旨在用于 mojang/forge 代码。他们期望返回接口返回的结果类型。如果他们没有得到合同/接口定义的内容,则代码将崩溃/无法编译。

似乎您正在尝试将接口用于自己的项目/api的特定目的。
考虑专门为您打算使用它的目的编写一个新接口。不要修改核心接口。

一个类可以继承多个接口,所以这不是问题。您可以实现和 forge/mojang 接口和您自己的。

于 2016-01-06T12:56:47.997 回答
0

您可以实现 mod 类。然后重写该方法。还要编写另一个方法,该方法将重载您实现的类中的方法。这样您就不必更改界面。

于 2016-01-05T19:52:10.330 回答