I have an use-case where I need the objects to provide sensible String
output in toString()
method (Not the default Object.toString()
output). I was thinking of enforcing toString()
method implementation through an Interface contract.
Something like,
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.
}
But as in the comment, it doesn't enforce implementing the toString()
method.
I have 2 workarounds,
Make the interface an abstract class,
abstract class TestInterface {
public abstract String toString();
}
class TestClass extends TestInterface {
// You will be enforced to implement the toString() here.
}
But this seems to be an overkill just to provide a contract. This will also mean the class cannot extend from any other class.
Change the method name to something else.
interface TestInterface {
public String toSensibleString();
}
class TestClass implements TestInterface {
// Should implement it here.
}
But this would mean, those classes which already override the toString()
method needs to have an unnecessary method. Also it would mean only those classes which know about the interface will get the proper String.
So, is there a way to provide a contract to (re)implement an existing method?
Note: I found this similar question but that's related to Groovy I guess (and his problem is not a problem in Java at all).