我有一个用例,我需要对象在String
方法中提供合理的toString()
输出(不是默认的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中的问题)。
答案 0 :(得分:5)
您无法通过接口在Object
方法上强制执行此类合同。你不应该。依靠Object.toString()
不是一个好主意。这是你最好的方法:
interface TestInterface {
public String toSensibleString();
}