Object Class in Java: Great Insights

In this post, we will dive deep into “Object Class in Java”. Let’s get started.

Object Class in Java

What is Object Class in Java?

The Object class in Java is a fundamental Class that serves as the root superclass for all other classes. It is defined in the java.lang package and provides essential methods that are inherited by all Java classes. Every class in Java is either directly or indirectly derived from the Object class.

Object Class Methods in Java

Let us look into the important methods inside the Object class in Java.

1. protected Object clone():This method creates and returns a copy of this object.Please visit Prototype for better understanding of the cloning concept.

2. boolean equals(Object obj):This method indicates whether some other object is “equal to” this one.

3. int hashCode():

This method returns a hash code value for the object.This method is supported for the benefit of hash tables such as those provided by HashMap.
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer

Please visit equals and hashCode for better understanding of equals and dashcode concepts.

4. void notify():This method wakes up a single thread that is waiting on this object’s monitor.

5. void notifyAll():This method wakes up all threads that are waiting on this object’s monitor.

6. void wait():This method causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

7. void wait(long timeout):This method causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

8. void wait(long timeout, int nanos): This method causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

Please visit wait, notify and notifyAll for better understanding of the wait and notify concepts.

9. protected void finalize():

This method is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.The finalize method is never invoked more than once by a Java virtual machine for any given object.

10. Class<?> getClass():This method returns the runtime class of this Object.

11. String toString():

This method returns a string representation of the object.In general, the toString method returns a string that “textually represents” this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The default toString() method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code of the object.

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

Sample Code using Methods of Object Class in Java

Let’s build a simple Class showcasing all the methods of Object Class in Java.

public class ObjectClassDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        // Create an object
        MyClass obj1 = new MyClass("Hello, World!");

        // Clone the object
        MyClass obj2 = (MyClass) obj1.clone();

        // Check if objects are equal
        boolean areEqual = obj1.equals(obj2);
        System.out.println("Are objects equal? " + areEqual);

        // Get hash codes
        int hashCode1 = obj1.hashCode();
        int hashCode2 = obj2.hashCode();
        System.out.println("Hash code of obj1: " + hashCode1);
        System.out.println("Hash code of obj2: " + hashCode2);

        // Notify and wait
        synchronized (obj1) {
            obj1.notify();
            try {
                obj1.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // Finalize method
        obj1.finalize();

        // Get runtime class
        Class<?> objClass = obj1.getClass();
        System.out.println("Runtime class: " + objClass.getName());

        // ToString method
        String objString = obj1.toString();
        System.out.println("Object as string: " + objString);
    }
}

class MyClass implements Cloneable {
    private String message;

    public MyClass(String message) {
        this.message = message;
    }

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        MyClass myClass = (MyClass) obj;
        return message != null ? message.equals(myClass.message) : myClass.message == null;
    }

    @Override
    public int hashCode() {
        return message != null ? message.hashCode() : 0;
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("Finalize method called");
        super.finalize();
    }

    @Override
    public String toString() {
        return "MyClass{" +
                "message='" + message + '\'' +
                '}';
    }
}

In this code, we create an instance of the MyClass class and demonstrate the usage of various methods from the Object class, including clone(), equals(), hashCode(), notify(), wait(), finalize(), getClass(), and toString(). The MyClass class also implements the Cloneable interface to enable cloning.

Conclusion: Object Class in Java

In conclusion, this article provided an in-depth exploration of the “Object Class in Java.” Here are the key points discussed:

  1. Object Class Overview: The Object class is a foundational class in Java that serves as the root superclass for all other classes. It is defined in the java.lang package and provides essential methods inherited by all Java classes.
  2. Important Object Class Methods: The article covered various significant methods from the Object class and their purposes, including clone(), equals(), hashCode(), notify(), notifyAll(), wait(), finalize(), getClass(), and toString().
  3. Sample Code: A comprehensive sample Java code was presented that demonstrated the usage of these Object class methods. The code showcased creating an object, cloning it, checking equality, obtaining hash codes, using synchronization with notify() and wait(), and other functionalities.

Leave a Reply

Your email address will not be published. Required fields are marked *