Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: design interface to force implementations to override toString

I'm developing an SPI and would like to define a Reportable interface such that any implementations must override toString() to something that is meaningful.

Is there any way in Java to write an interface such that any of its concrete implementations must override Object's toString()? For instance:

public interface Reportable
{
    public String toString();
}

public class Widget implements Fizz, Buzz, Reportable
{
    // ...

    @Override
    public String toString()
    {
        // ...
    }
}

I know the above code doesn't force this kind of behavior, but is an example of what I'm looking for, i.e. if Widget doesn't override toString() you get a compile error because its violating the interface contract.

like image 380
IAmYourFaja Avatar asked Apr 07 '12 12:04

IAmYourFaja


People also ask

Can we override toString method in interface?

We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.

Do you need to override the toString method in Java?

A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.


2 Answers

No, you can't do this. I'd suggest you choose a different method name, e.g.

public interface Reportable
{
    String createReport();
}

That will force implementations to write an appropriate method. toString() is already somewhat vague in its intention - whether it's for debug representations, user-visible representations (at which point you need to ask yourself about locales etc). Adding another meaning doesn't seem like a good idea to me.

like image 85
Jon Skeet Avatar answered Sep 21 '22 01:09

Jon Skeet


What I understand is that you want to create a set of classes which neatly give their string representations. So that when something like System.out.println(yourobject) is called it shows meaningful data.

You cannot force your subclasses to override toString. But you can do something like this.

abstract class MyBase
{
    abstract String getNiceString();
    @Override
    public String toString()
    {
        return getNiceString();
    }
}
like image 22
Partha Pratim Sirker Avatar answered Sep 21 '22 01:09

Partha Pratim Sirker