Object Class in Java

The Object class in Java is a fundamental class in the Java programming language. It is the superclass of all other classes, and provides methods for dealing with objects in a general way. In this blog post, we will discuss the important methods and use cases of the Object class in Java.

The Key Methods of Object Class

The Object class provides a set of crucial methods that can be utilized by any class in Java. Let’s explore some of the most commonly used methods with accompanying code examples and their expected output.

equals(Object obj)

The equals() method allows for the comparison of two objects for equality. By default, the equals() method checks for reference equality.

import java.util.Objects;
class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

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

public class EqualsMethodDemo {
    public static void main(String[] args) {
        Person person1 = new Person("Radha");
        Person person2 = new Person("Radha");
        Person person3 = new Person("Krishnan");

        System.out.println(person1.equals(person2)); // Output: true
        System.out.println(person1.equals(person3)); // Output: false
    }
}

hashCode()

The hashCode() method returns a unique integer value for each object. This method is often overridden when the equals() method is customized to ensure consistency between the two. It is widely used in hash-based data structures like HashMap and HashSet.

import java.util.Objects;

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}

public class HashCodeMethodDemo {
    public static void main(String[] args) {
        Person person1 = new Person("Radha");
        Person person2 = new Person("Radha");

        System.out.println(person1.hashCode()); // Output: 78717901
        System.out.println(person2.hashCode()); // Output: 78717901
    }
}

toString()

The toString() method provides a textual representation of the object. It is good to override subclasses to return meaningful and descriptive information about the object’s state while printing the object itself.

See the example below:

class Person {
	private String name;
	private int age;

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

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

public class ToStringMethodDemo {
	public static void main(String[] args) {
		Person person = new Person("Radha", 30);

		System.out.println(person); // Output: Person{name='Radha', age=30}
	}
}

If we don’t override the toString() method then it will print the garbage value. See the example below:

class Person {
	private String name;
	private int age;

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

}

public class ToStringMethodDemo {
	public static void main(String[] args) {
		Person person = new Person("Radha", 30);

		System.out.println(person); // Output: Person@75a1cd57
	}
}

Although, it allows us to use the toString() method like:

String objectValue = person.toString();

It still prints the garbage value like:

Person@75a1cd57

Hence, it is recommended to override toString() method if you want to print the nicely formatted information of the class object.

getClass()

The getClass() method returns the runtime class of an object. It is frequently used to obtain metadata about the object’s class, such as its name or the interfaces it implements.

class Person {
	// Class implementation

	public void printClassName() {
		System.out.println("Class: " + super.getClass().getName());
	}
}

public class GetClassMethodDemo {
	public static void main(String[] args) {
		Person person = new Person();
		person.printClassName(); // Output: Class: Person
	}
}

finalize()

The finalize() method is invoked by the garbage collector before reclaiming an object’s memory. It can be overridden to perform necessary cleanup operations or resource deallocation.

class Person {
	// Class implementation

	@Override
	protected void finalize() throws Throwable {
		System.out.println("Finalizing Person object...");
		// Cleanup operations
		super.finalize();
	}
}

public class FinalizeMethodDemo {
	public static void main(String[] args) {
		Person person = new Person();
		person = null;
		System.gc(); // Request garbage collection
	}
}

Output:

Finalizing Person object...

Note: The finalize() method is deprecated from Java 9. I am adding it for reference. You should not use this method. You can read about this deprecation on the official site.

clone()

The clone() method creates a shallow copy of the object. The copy of the object will have the same values as the original object, but it will be a separate object.

class Person implements Cloneable {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Person(String name) {
		super();
		this.name = name;
	}

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

public class CloneMethodDemo {
	public static void main(String[] args) {
		Person person1 = new Person("Radha");
		try {
			Person person2 = (Person) person1.clone();
			System.out.println(person1.equals(person2)); // Output: false
			System.out.println(person1.getName().equals(person2.getName())); // Output: true
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
	}
}

Since all classes implicitly inherit from the Object class, it is possible to override its methods in subclasses to tailor their behavior to specific requirements. This allows developers to define customized equality checks, change the object’s string representation, or implement additional functionality.

There are other important methods in Object class like wait() and notify(). There is a separate post on this. You can read the wait() and notify() methods with proper examples.

FAQs

What is the purpose of the hashCode() method in the Object class?

The hashCode() method returns a hash code value for an object. This value is often used in data structures like hash tables to optimize and speed up retrieval operations. It’s essential to override hashCode() when the equals() method is overridden to ensure consistent behavior.

What is the purpose of the getClass() method in the Object class?

The getClass() method in the Object class returns the runtime class of an object. It is often used for runtime type checking and can be helpful when working with polymorphism.

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments