1
我有一个用例,我需要的对象提供合理String
输出toString()
方法(不是默认的Object.toString()
输出)。我正在考虑通过Interface合同强制实施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()
方法的类需要有一个不必要的方法。这也意味着只有那些知道接口的类才能获得正确的String。
那么,有没有提供合同(重新)执行现有方法的的方法吗?
注意:我发现this similar question但这与Groovy有关我猜(他的问题在Java中根本不是问题)。
如果你使用的Java 8中,您可以使用一个界面,默认的方法实现,其中抛出一个异常,但这种执法是在运行时,而不是编译时 –
@RaduToader:[你不能在接口中实现一个'默认的String toString()'方法。](http://stackoverflow.com/q/24016962/521799) –
复制到http://stackoverflow.com/questions/1718112/tostring-equals-and-hashcode-in-an-interface – PKuhn