Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force toString() implementation in subclasses

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

like image 454
Dopele Avatar asked Jan 03 '12 22:01

Dopele


People also ask

Is toString inherited by all classes?

Every class in Java inherits the default implementation of the toString method.

How is toString implemented?

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.

What happen if we override toString () 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.


2 Answers

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();
}
like image 183
kithril Avatar answered Oct 14 '22 23:10

kithril


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();
  }
}
like image 30
Aravind Yarram Avatar answered Oct 14 '22 23:10

Aravind Yarram