Fundamentals 10 min read

Understanding Java’s Object Class: Core Methods, Cloning, and Equality

The article explains Java's Object class as the root of all classes, details its fundamental methods such as clone, equals, hashCode, toString, finalize and getClass, illustrates shallow vs. deep copying, shows how to override equals with a Book example, and warns about using finalize for cleanup.

Lisa Notes
Lisa Notes
Lisa Notes
Understanding Java’s Object Class: Core Methods, Cloning, and Equality

The Object class sits at the top of Java's class hierarchy and provides every class with a set of basic methods.

Key methods include clone() (shallow copy), equals(Object obj) (reference comparison), finalize() (GC callback), getClass() (returns a Class object), hashCode() (object hash), and toString() (string representation). All of them are declared in java.lang.Object.

Cloning creates a copy of an existing object. By default clone() performs a shallow copy; to obtain a deep copy a subclass must override the method. An object can be cloned only if its class implements Cloneable; otherwise clone() throws CloneNotSupportedException. The syntax is simply: object.clone(); If a class holds references to external objects, its clone() should also clone those referenced objects; otherwise the original and cloned objects will share the same external state.

The equals() method compares object references. In many applications a logical equality based on object content is required, so equals() is overridden. The article provides a concrete example with a Book class that overrides equals() to compare the id field, and a test class that demonstrates two distinct Book instances being considered equal because their id values match:

class Book {
    private String id;
    Book(String id) { this.id = id; }
    public String getId() { return this.id; }
    public boolean equals(Object obj) {
        if (obj instanceof Book) {
            return id.equals(((Book) obj).getId());
        } else {
            return false;
        }
    }
}

public class BooksEqualsTest {
    public static void main(String[] args) {
        Book book1 = new Book("20220101");
        Book book2 = new Book("20220101");
        if (book1.equals(book2)) {
            System.out.println("两个对象相等");
        } else {
            System.out.println("两个对象不相等");
        }
    }
}

The program prints 两个对象相等, showing that logical equality depends on the overridden method rather than reference identity.

The finalize() method is a protected callback invoked by the garbage collector when an object becomes unreachable. The default implementation does nothing; overriding it to release resources is discouraged because the timing of its execution is nondeterministic and it may never run.

The getClass() method is final and cannot be overridden. It returns a Class object that provides metadata such as the simple name, superclass, and implemented interfaces. Example usage:

void getClassName(Object obj) {
    System.out.println("对象所属的类是" + obj.getClass().getSimpleName());
}

The hashCode() method returns an integer hash value, typically derived from the object's memory address. When equals() is overridden, hashCode() must also be overridden to maintain the contract that equal objects have equal hash codes.

The toString() method returns a string representation of the object. Overriding it yields more readable output, for example: id:0202:Java 从入门到精通 Overall, the article walks through each of these core methods, explains their default behavior, shows when and how to override them, and provides concrete code snippets to illustrate proper usage.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavafinalizecloneequalshashCodegetClassObject class
Lisa Notes
Written by

Lisa Notes

Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.