I have an abstract parent class, and I would like it to force all subclasses to implement toString() method.
However putting:
public abstract String toString();
is causing a compilation error:
Repetitive method name/signature for method 'java.lang.String toString()' in class ...
I believe this might be caused by groovy already having toString defined.
Thanks
Every class in Java inherits the default implementation of the toString method.
The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called. Here are some of the advantages of using this method.
By overriding the toString( ) method, we are customizing the string representation of the object rather than just printing the default implementation. We can get our desired output depending on the implementation, and the object values can be returned.
This works for me. Is this new or did others just miss it?
public abstract class Filterable
{
@Override
public abstract String toString();
}
public class ABC extends Filterable
{
// Won't compile without toString();
}
The toString()
is part of the java.lang.Object
class which already has a default implementation for it. So you essentially can't force the sub-classes to implement it. If you want to force this kind of behavior (not sure why) then you can do something like below
public class abstract SuperClass {
public abstract String myToString();
public String toString() {
return myToString();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With