Java: design interface to force implementations to override toString

后端 未结 2 1951
遇见更好的自我
遇见更好的自我 2021-01-07 23:05

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

2条回答
  •  星月不相逢
    2021-01-07 23:16

    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();
        }
    }
    

提交回复
热议问题