An overview of the Object class

  • The java.lang.Object class is the root class in the Java language, the parent class of all classes.

    If a class does not specify a parent class, it inherits from the Object class by default. Such as:

    public class MyClass/ *extends Object* /{
      	// ...
    }
    Copy the code
  • According to the JDK source code and the Object API documentation, the Object class contains 11 methods. Today we’ll focus on two of them:

  • Public String toString() : Returns a String representation of this object.

  • Public Boolean equals(Object obj) : Indicates whether some other Object is “equal” to this Object.

  • Public String toString() : Returns a String representation of the object, which is the object’s type name +@+ memory address value.

Because the toString method returns a memory address, and you often need to get a string representation based on an object’s attributes in development, you also need to override it.

Override the toString method

If you don’t want to use the default behavior of the toString method, you can override it. In IntelliJ IDEA, you can click Generate in the Code menu… , or you can use the shortcut Alt + Insert and click the toString() option. Select the member variables to include and determine.

Tip: When we print the object name directly using the output statement, we actually call its toString() method from the object.

  • The toString method returns the string content format by default: the type of the object +@+ the address value of a hexadecimal number
  • When you print an object, you print the contents of the string returned by the object’s call to toString
  • If you don’t want to print an address, you can override the toString method and specify the format of the string content to be returned —->

An overview of equals methods

  • public boolean equals(Object obj): Indicates whether another object is “equal” to this object.

Use of equals method

Default address comparison

The equals() method of the Object class defaults to ==, which compares the addresses of two objects

Object content comparison

If you want to compare the contents of objects, that is, two objects are the same if all or part of the specified member variables are the same, you can override equals.

This code takes into account things like empty objects and consistent types, but method content is not unique. Most ides can automatically generate the equals method’s code content. In IntelliJ IDEA, Generate can be used in the Code menu… Option, or you can use the shortcut Alt + Insert and select equals() and hashCode() for automatic code generation.

Other methods in the Object class, such as hashCode, will be studied in the future.