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

后端 未结 4 882
爱一瞬间的悲伤
爱一瞬间的悲伤 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 02: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.

提交回复
热议问题