What are the original reasons for ToString() in Java and .NET?

后端 未结 4 903
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 02:01

I\'ve used ToString() modestly in the past and I\'ve found it very useful in many circumstances. However, my usage of this method would hardly justify to put th

4条回答
  •  余生分开走
    2020-12-06 03:02

    I can think of two technical reasons for defining toString() on java.lang.Object.

    • The PrintStream.print(Object) API (for example) depends on Object.toString();

    • The String concatenation operator + depends on Object.toString() in the case where one of the operands is a non-String reference type.

    As an alternative, it would have been possible to define an interface (say) Printable that offered a toString()-like method and defined the above to require a Printable. (And that would avoid the puzzlement that arises when a newbie tries to print an object that doesn't overload toString()).

    However, it is really convenient that print (etc) and + concatenation just work for everything. And I'm sure that's why Java was designed that way.

    EDIT - in response to this followup question from the OP:

    Static hypothetical FromString vs Serialization: sure, but that's quite a different story, right?

    Assuming that I am parsing your syntax correctly ...

    The goal of Object serialization is to provide a flat representation that can be reliably and efficiently deserialized. The goal of toString() is to provide a textual representation that is easy to read. In practice, "easy to read" and "reliably and efficiently deserializable" are contradictory.

提交回复
热议问题