Java SE study notes ---> Advanced class features ---> toString() method

Overview :

  The toString() method is very common in object-oriented and used very frequently. Like the equals() method, it is also a method defined in the Object class.

Source code in jdk:

The ToString() method in the java.lang.Object class is defined as follows:

public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

 

Knowledge points:

1. The toString() method is defined in the Object class. Its return value is of type String, returning the class name and its reference address

  Such as:

public class TestToString {
    public static void main(String[] args) {
        Person p1 = new Person("AA", 10);
        System.out.println(p1.toString());  //com.klx.learn7.Person@d17
        System.out.println(p1);    //com.klx.learn7.Person@d17

    }
}

    com.klx.learn7.Person@d17

    @The class where the front "com.klx.learn7.Person" object is located

    The "d17" after @ is the first address value of the object's entity in the heap space (hexadecimal)

 

2. When we print a reference to an object, the toString() method of the object is actually called by default, and the toString() method will also be called automatically when linking String with other types of data.

 

  example:

Date now=new Date();
System.out.println(“now=”+now);  
相当于:System.out.println(“now=”+now.toString());//now=Date@122345

 

3. When the class of the object we print does not override the toString() method in Object, then the toString() method defined in Object is called to return the class where the object is located and the header of the corresponding heap space object entity. address value.

 

4. When the class of the object we print overrides the toString() method, the toString() method we override is called.

For example: define the following in the class:

public String toString() {
        return "Person: name=" + name + " age:" + age;
    }

then when we print the previous

System.out.println(p1.toString());  //Person: name=AA age:10
System.out.println(p1);    //Person: name=AA age:10

 

5. Generally speaking, when designing and creating a new class, provide a toString() method.

Often rewritten like this: Return the property information of the object.

It can be implemented manually, or it can be called automatically by eclipse (Source--->Generate toString())

 

6. The String class or Date class, wrapper class, File class, etc. in java have implemented the rewrite of the toString() method in the Object class

 

7. The toString() method can be rewritten in the user-defined type as needed. For example, the String class overrides the toString() method to return the value of the string.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325814857&siteId=291194637