SoFunction
Updated on 2025-05-17

Detailed explanation of common methods and application scenarios of object class in Java

In Java,ObjectA class is the root parent class of all classes, and the methods it provides will be inherited by all subclasses. The following isObjectCommon methods of classes and their typical application scenarios:

1. toString()

  • effect: Returns the string representation of the object (default format:Class name @ hash code)。

  • Rewrite the scene

    • When printing objects, more readable information (such as logs, debugging) is required.

    • Collection of()Output dependent elementstoString()

  • Example

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }

2. equals(Object obj)

  • effect: Compare whether two objects are "logically equal" (the default comparison memory addresses, that is,==)。

  • Rewrite the scene

    • Equalities need to be judged based on the object content (rather than the address) (such as value objects, DTO).

    • Collection class (such asHashSet()) Rely on this method.

  • rule

    • Must be rewrittenhashCode()To ensure consistency (ifequalsreturntruehashCodeMust be the same).

    • Satisfies reflexivity, symmetry, transmission and consistency.

  • Example

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != ()) return false;
        Person person = (Person) obj;
        return age ==  && (name, );
    }

3. hashCode()

  • effect: Returns the hash code of the object (the hash value of the memory address by default).

  • Rewrite the scene

    • Object asHashMapkey orHashSetelement when.

    • Must be withequals()Logical consistency.

  • Example

    @Override
    public int hashCode() {
        return (name, age); // Use tool classes to simplify calculation}

4. getClass()

  • effect: Returns the runtime class of the object (ClassObject).

  • Application scenarios

    • Reflection operations (such as dynamically creating instances and calling methods).

    • Precisely judge object type (better thaninstanceof)。

  • Example

    Class<?> clazz = ();
    (()); // Fully qualified name of the output class

5. clone()

  • effect: Create a shallow copy of the object.

  • Application scenarios

    • When copying objects is required (requires implementationCloneableMark the interface, otherwise throw itCloneNotSupportedException)。

    • Deep copy needs to be manually rewrite (recursively copy the reference type field).

  • Example

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return (); // Light copy}

6. finalize() (deprecated)

  • effect: Cleanup method called before the object is garbage collected (Java 9+ is marked as abandoned).

  • Alternatives:useAutoCloseable(liketry-with-resources) or explicit cleanup method.

7. wait(), notify(), notifyAll()

  • effect: Waiting/notification mechanism for inter-thread communication (must be insynchronizeduse in blocks).

  • Application scenarios

    • Producer-consumer model.

    • Multithreaded collaborative tasks (such as thread pool task scheduling).

  • Example

    synchronized (lock) {
        while (conditionNotMet) {
            (); // Release the lock and wait    }
        // Perform an operation    (); // Wake up other threads}

Summary of core methods

method Typical application scenarios Things to note
toString() Log output, debugging Rewrite all classes are recommended
equals()/hashCode() Collection operations, object comparison Must be rewritten at the same time to keep the logic consistent
getClass() Reflection, type judgment Returns the runtime class object
clone() Object copy Deep copy needs to be implemented manually
wait()/notify() Multithreaded synchronization Need to matchsynchronizeduse

Why is it important?

  • Default behavior: All classes inheritanceObject, understand its method to avoid getting stuck (such as wrong collection comparison).

  • Framework dependency:likeHashMaprelyhashCode()andequals(), serialization dependenciestoString()

  • Design Specifications: Correct rewriting of these methods is a basic requirement of object-oriented design.

Summarize

This is the article about the common methods and application scenarios of the object class in Java. For more related common methods of the object class, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!