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

主宰稳场 提交于 2019-11-27 22:22:43

It was initially added to Object for debugging and logging purposes. You can deduce this if you look at the JavaDoc for Object.toString (http://java.sun.com/javase/6/docs/api/java/lang/Object.html#toString()), as it outputs the classname, followed by @, followed by the unsigned hexadecimal representation of the hash code of the object. The only place I can see this being very useful is in a log or console.

But the Java creators intentionally left this method non-final so subclasses could (and should) override it to instead output more subclass-specific information. They could have just implemented the JVM such that passing an object into any method that required a string, it would generate that hash value above and pass it into the method, but instead they were nice and implemented it as a method that you could so conveniently override.

And its implemented at the Object level so they you can safely assume any object can be written out to a log/console. Its a convenient assumption in the Java language.

Without discussing its merits, I believe this has its roots in the inspirational language for C# - Java. The reason it was created (for both languages) was to provide a way to get a string representation of an instance of any object, including support for different cultures. Simple as that.

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.

I guess it was just considered useful that any object can have a string representation, if only for debugging purposes...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!