Tenth: Always overwrite the ToString () method

Source: Internet
Author: User

The ToString () method provided by the object class is as follows:

Public String toString ()

Return GetClass (). GetName () + "@" + integer.tohexstring (Hashcode ());


If we print an object directly, we call the ToString () method of the object, and if we do not overwrite the ToString () method for that class,

We can see the ToString () method, which returns "class name @ hash value hex".

The general Convention for the ToString () method is to return the current object as "concise, but informative, and easy to read expression".

The ToString () method of an object is called automatically in the following cases:

println (), printf (), string-linked operator (+), assert, when printed by the debugger.

In real-world applications, the toString () method should return all the interesting information contained in the object.

For some value classes, the ToString () method is provided, the value type is output as a string type, and a matching static factory method or constructor is provided, and the string type of the value is converted to

The type of the value itself. Many value classes in the Java Platform Class Library Take this approach, such as biginteger,bigdecimal and most of the basic type wrapper classes. This facilitates the programmer in the object type

and the type of string to convert between.

Tenth: Always overwrite the ToString () method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.