View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Object Class in Java: Methods, Usage, and Examples Explained

Updated on 19/05/20255,769 Views

The Object class is a fundamental part of the Java programming language. It serves as the root class for all other classes in Java. Whether you create a custom class or use built-in Java classes, they all implicitly extend the Object class. Understanding the methods of the Object class is crucial because they provide essential functionalities that are used in everyday Java programming.

Enhance your Java skills with expert-led training. Check out upGrad’s Software Engineering course and learn how to apply Java in real-world projects.

Explanation of the Object Class

The Object class is a part of java.lang package, and it is the superclass of all classes in Java programming language. This means that every class in Java, either directly or indirectly, inherits the methods of the Object class.

Key Features of the Object Class

  • It provides methods for common operations like object comparison, converting to a string representation, and getting the runtime class of an object.
  • Methods like hashCode(), equals(), toString(), and getClass() can be overridden to suit specific needs in user-defined classes.
  • The class also provides methods related to concurrency, object cloning, and garbage collection.

Why is the Object Class Important?

Since every Java class is a descendant of the Object class, the methods defined in it are inherited by all classes. This makes the Object class the backbone of object management in Java. From comparing objects to managing memory and handling threads, the Object class offers core methods that every Java programmer must understand.

Object Class Methods in Java – Summary Table

Modifier and Type

Method

Description

public String

toString()

Returns a string representation of the object. Typically overridden for clarity.

public int

hashCode()

Returns a hash code value for the object, used in hash-based collections.

public boolean

equals(Object obj)

Compares this object to the specified object for logical equality.

public final Class<?>

getClass()

Returns the runtime class of the object.

protected void

finalize()

Called by the garbage collector before object is reclaimed. Used for cleanup.

protected Object

clone()

Creates and returns a copy of the object. Requires implementation of Cloneable.

public final void

wait()

Causes the current thread to wait until another thread invokes notify().

public final void

wait(long timeout)

Waits for the specified time in milliseconds.

public final void

wait(long timeout, int nanos)

Waits for the specified time (in ms + ns).

public final void

notify()

Wakes up a single thread waiting on this object’s monitor.

public final void

notifyAll()

Wakes up all threads waiting on this object’s monitor.

Java powers the backend. Generative AI drives the future. Equip yourself with leadership skills in AI through this executive programme.

Object Class Methods in Java Explained

The methods provided by the Object class in Java form the foundation of working with objects in Java programming. Let's explore the most commonly used object class methods:

1. toString() Method

The toString() method is used to convert an object into a string representation. Every class in Java inherits this method from the Object class, and it can be overridden to provide a more meaningful description of the object.

Example:

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

public class Main {
    public static void main(String[] args) {
        Person p = new Person("Janvi", 25);
        System.out.println(p);
    }
}

Output:

Person{name='Janvi', age=25}

Explanation: In the example above, the toString() method is overridden to provide a meaningful string representation of the Person object. By default, it returns the class name and the memory reference.

Already confident in Java? Level up with in-demand cloud and DevOps knowledge through upGrad’s Professional Certificate Program.

2. hashCode() Method

The hashCode() method returns a hash code for the object, which is used in hashing data structures like HashMap, HashSet, and Hashtable. The default implementation of hashCode() in the Object class typically returns the memory address of the object.

Example:

class Car {
    String model;
    int year;

    Car(String model, int year) {
        this.model = model;
        this.year = year;
    }

    @Override
    public int hashCode() {
        return model.hashCode() + year;
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car("Tesla", 2022);
        System.out.println(car.hashCode());
    }
}

Output:

1553668604

This example shows how the hashCode() method is used to return a unique identifier for each Car object, which is important for hash-based collections. 

NOTE: Different outputs may appear on different systems due to variations in how String.hashCode() is internally calculated across JVM implementations or versions.

3. equals(Object obj) Method

The equals() method compares the current object with another object for equality. By default, it checks for reference equality, but it can be overridden to check for logical equality between two objects (i.e., comparing the content).

Example:

class Book {
    String title;
    String author;

    Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Book book = (Book) obj;
        return title.equals(book.title) && author.equals(book.author);
    }
}

public class Main {
    public static void main(String[] args) {
        Book book1 = new Book("Java Basics", "John");
        Book book2 = new Book("Java Basics", "John");
        System.out.println(book1.equals(book2)); // true
    }
}

Output:

true

In this example, the equals() method compares two Book objects by their title and author fields. If the fields match, it returns true.

4. getClass() Method

The getClass() method returns the Class object that represents the runtime class of the object. This method is often used in reflection to dynamically obtain information about the object's class.

Example:

class Animal {}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal();
        System.out.println(animal.getClass().getName());
    }
}

Output:

Animal

This example demonstrates how to use the getClass() method to retrieve the class name of an object dynamically at runtime.

5. finalize() Method

The finalize() method is called by the garbage collector before an object is destroyed. This method is useful for releasing system resources like file handles or database connections before an object is reclaimed by the garbage collector.

Example:

class Resource implements AutoCloseable {
    public void doSomething() {
        System.out.println("Using resource");
    }

    @Override
    public void close() {
        System.out.println("Resource closed");
    }
}

public class Main {
    public static void main(String[] args) {
        try (Resource res = new Resource()) {
            res.doSomething();
        }
    }
}

Output:

Using resource  

Resource closed

Explanation:

In this code, the finalize() method is overridden to print a message before the object is garbage collected. However, since finalize() is deprecated, the compiler shows a warning. The output confirms successful execution but advises against using finalize().

6. clone() Method

The clone() method is used to create and return a copy of the object. By default, it performs a shallow copy, but you can override it to create a deep copy if needed.

Example:

class Laptop implements Cloneable {
    String brand;
    int year;

    Laptop(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Laptop laptop1 = new Laptop("Dell", 2022);
        Laptop laptop2 = (Laptop) laptop1.clone();
        System.out.println(laptop1.brand + " " + laptop2.brand);
    }
}

Output:

Dell Dell

Explanation:

In this example, the clone() method is overridden to provide a shallow copy of the Laptop object.

7. Concurrency Methods: wait(), notify(), and notifyAll()

These methods are part of the Object class and are used for thread synchronization and communication. The wait() method causes the current thread to release the lock and enter a waiting state. The notify() and notifyAll() methods are used to wake up one or all threads that are waiting on the object.

Example:

class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
        notify();
    }

    public synchronized int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            synchronized (counter) {
                while (counter.getCount() < 5) {
                    try {
                        counter.wait();
                    } catch (InterruptedException e) {}
                }
                System.out.println("Count reached 5!");
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                counter.increment();
                System.out.println("Incremented count: " + counter.getCount());
            }
        });

        t1.start();
        t2.start();
    }
}

Output:

Incremented count: 1

Incremented count: 2

Incremented count: 3

Incremented count: 4

Incremented count: 5

Count reached 5!

Explanation:

This example demonstrates how the wait(), notify(), and notifyAll() methods can be used for synchronizing threads.

Conclusion

The Object class in Java is integral to the Java language as it provides essential methods for object comparison, memory management, thread synchronization, and more. Understanding and overriding these methods in your custom classes can lead to more efficient and organized code. The methods like toString(), hashCode(), equals(), and clone() are frequently used across Java applications.

Mastering these methods not only helps with better object handling but also improves the overall performance and maintainability of Java programs. Whether you're debugging, implementing collections, or managing object states, the methods from the Object class are fundamental tools in your Java programming toolkit.

FAQs

1. What is the Object class in Java?

The Object class is the root of the Java class hierarchy. Every class in Java directly or indirectly inherits from it. It provides core methods like toString(), equals(), hashCode(), and others that enable fundamental object behavior such as comparison, representation, and synchronization.

2. Why is Object class the superclass of all classes in Java?

Java follows a single-rooted inheritance model to ensure consistency. Making Object the superclass of all classes allows the JVM to treat every object uniformly, enabling features like polymorphism, collection handling, and method overriding with consistent default behavior.

3. What are the methods provided by the Object class?

Key methods include toString(), equals(), hashCode(), getClass(), clone(), finalize(), and synchronization-related methods like wait(), notify(), and notifyAll(). These methods help in object representation, identity, lifecycle management, and inter-thread communication.

4. Can we override methods of the Object class?

Yes, most methods of the Object class can be overridden, such as toString(), equals(), and hashCode(), to provide class-specific behavior. However, methods like getClass() and wait() are final, so they cannot be overridden.

5. What is the purpose of the toString() method in Java?

The toString() method returns a string representation of the object. By default, it returns the class name followed by the object's hash code. Overriding it helps display object content meaningfully, especially useful for debugging or logging.

6. How does equals() differ from == in Java?

The equals() method checks for logical equality (whether objects have the same value), while == checks for reference equality (whether both references point to the same object in memory). Overriding equals() allows comparing content meaningfully.

7. What is the use of the hashCode() method?

The hashCode() method returns an integer value, used in hashing-based collections like HashMap or HashSet. It works alongside equals() to identify object uniqueness. If two objects are equal, their hash codes must also be equal for correct collection behavior.

8. Is the finalize() method still used in Java?

The finalize() method was used for cleanup before object destruction but is now deprecated due to unpredictability and performance issues. Modern Java recommends using try-with-resources or Cleaner for resource management instead of relying on finalize().

9. How does getClass() work in Java?

The getClass() method returns the runtime class of an object as a Class<?> instance. It helps in reflection, where you want to inspect or manipulate class metadata dynamically at runtime without knowing the class type beforehand.

10. What is the clone() method in Java?

The clone() method creates and returns a copy of the object. To use it, a class must implement the Cloneable interface. It performs a shallow copy by default and can be overridden for deep copying or custom behavior.

11. What are wait(), notify(), and notifyAll() methods used for?

These methods are used for thread communication and synchronization. wait() pauses a thread until another thread invokes notify() or notifyAll() on the same object. They help manage multi-threaded scenarios where threads share resources and need coordination.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.