【问题标题】:Enforce (re)implementing of existing method through interface contract? [duplicate]通过接口契约强制(重新)实现现有方法? [复制]
【发布时间】:2015-09-07 12:44:36
【问题描述】:

我有一个用例,我需要对象在toString() 方法中提供合理的String 输出(不是默认的Object.toString() 输出)。我正在考虑通过接口契约强制执行 toString() 方法。

类似的,

interface TestInterface {
    public String toString();
}

class TestClass implements TestInterface {
    // But there's no need to implement toString() since it's already present as part of Object class.
}

但正如评论中所述,它并没有强制实现toString() 方法。

我有 2 个解决方法,

使接口成为抽象类

abstract class TestInterface {
    public abstract String toString();
}

class TestClass extends TestInterface {
    // You will be enforced to implement the toString() here.
}

但这似乎只是为了提供一份合同。这也意味着该类不能从任何其他类扩展。


将方法名称更改为其他名称。

interface TestInterface {
    public String toSensibleString();
}

class TestClass implements TestInterface {
    // Should implement it here.
}

但这意味着,那些已经覆盖toString() 方法的类需要有一个不必要的方法。这也意味着只有那些知道接口的类才能获得正确的字符串。


那么,有没有办法提供合同来(重新)实现现有方法?

注意:我找到了this similar question,但我猜这与 Groovy 有关(而且他的问题在 Java 中根本不是问题)。

【问题讨论】:

  • 如果您使用 java 8,您可能会使用带有默认方法实现的接口,这会引发异常,但这种类型的强制执行是在运行时,而不是在编译时
  • @RaduToader 不幸的是你不能。 It is a compile-time error if a default method is override-equivalent with a non-private method of the class Object, because any class implementing the interface will inherit its own implementation of the method. 即使你可以,你的默认方法也永远不会被调用,因为Object 已经提供了更具体的实现。

标签: java interface


【解决方案1】:

您不能从接口对Object 方法强制执行此类合同。你不应该。依赖Object.toString() 不是一个好主意。这是您最好的方法:

interface TestInterface {
    public String toSensibleString();
}

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 2015-05-08
    • 1970-01-01
    • 2013-02-19
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    相关资源
    最近更新 更多