Object class in java

The Object class, present in the java.lang package, is the root class of the Java class hierarchy. Every class in Java implicitly or explicitly inherits from the Object class. It provides basic methods that all Java objects inherit and can use.

Overview of Object Class

Here is a list of methods provided by the Object class

  • protected Object clone() throws CloneNotSupportedException
  • public boolean equals(Object obj)
  • protected void finalize() throws Throwable 
  • public final Class<?> getClass()
  • public int hashCode()
  • public final void notify()
  • public final void notifyAll()
  • public String toString()
  • public final void wait() throws InterruptedException
  • public final void wait(long timeout) throws InterruptedException
  • public final void wait(long timeout, int nanos) throws 

lets explore each method of Object class


public final Class<?> getClass()

  • Returns the runtime class of the object.
  • Used to obtain the class object that represents the runtime class of this object.
  • Often used in conjunction with reflection to obtain information about the class.
Code Example
Output
car

protected Object clone() throws CloneNotSupportedException

  • Creates and returns a copy of the object.
  • Used to create a new instance that is a copy of the existing instance. Requires the class to implement the Cloneable interface.
  • The clone() method creates a new instance of the class and initializes all its fields with the same values as the original object.
  • Only classes that implement the Cloneable interface can be cloned. If the Cloneable interface is not implemented, clone() throws a CloneNotSupportedException.
  • The default clone() method performs a shallow copy, meaning it copies the object and references to other objects, not the objects they point to.
Code Example

public int hashCode()

  • Returns a hash code value for the object.
  • Used in hashing-based collections like HashMap, HashSet and other hash-based collections, hashCode() is used to find the bucket where the object should be placed. The default implementation provided by Object class returns a distinct integer for each object.
  • Returns a hash code value for the object, typically derived from the memory address of the object.
  • Should be overridden whenever equals() is overridden.
  • Benificial for when we search the objects, comparing the two or more objects.
  • Whenever you need to sort or search through a collection of objects, the equals() and hashCode() methods are essential.
  • If two objects are equal according to equals(Object obj), they must have the same hash code.
  • If two objects are not equals by .equals() method then there is no restriction on hasCodes may be equal or may not be equal.
  • If hashCode of two objects are equal then we cant conclude anything about .equals() method it may return true or false.

The hashCode() And equals() Contract

  • equals() and hashCode() methods are bound together by a joint contract that specifies if two objects are considered equal using the equals() method, then they must have identical hashcode values.
  • So to be truly safe, your rule of thumb should be if you override equals(), override hashCode() as well. 
  • 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, provided that no information used in equals() comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application
  • If two objects are equal according to the equals(Object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.

Usage in Collections:

  • In HashMap, HashSet, and other hash-based collections, hashCode() is used to find the bucket where the object should be placed.
  • The equals() method is used to compare the objects in the bucket to ensure uniqueness.
Code Example
Output
this.id: 3, hashCode=> 34
this: Student@22
this.id: 3, hashCode=> 34
obj: Student@22
this=> id1: 3, name1: S1, age1: 25
obj=> id2: 3, name2: S2, age2: 28
s1.equals(s2): true
this.id: 3, hashCode=> 34
this: Student@22
this.id: 4, hashCode=> 35
obj: Student@23
this=> id1: 3, name1: S2, age1: 28
obj=> id2: 4, name2: S2, age2: 28
s2.equals(s3) false
this.id: 3, hashCode=> 34
s1 hash: 34
this.id: 3, hashCode=> 34
s2 hash: 34

Overriding hashCode():

  • The hashCode() method is overridden to compute the hash code based on the id field.
  • Objects.hash(this.id) is used to compute the hash code.
  • The method prints the id and the computed hash code for debugging purposes.

Overriding equals():

  • The equals() method is overridden to compare Student objects based on the id field.
  • The method checks if the obj is the same as this using obj == this.
  • It then checks if the obj is null or not an instance of the Student class.
  • Finally, it compares the id fields of the two Student objects to determine equality.

public boolean equals(Object obj)

  • To compare two objects for equality.
  • Indicates whether some other object is "equal to" this one. ( `this` refer to current class object ).
  • Used to compare objects for equality. The default implementation provided by Object class checks for object reference equality (i.e., this == obj).
  • Whenever you need to sort or search through a collection of objects, the equals() and hashCode() methods are essential.

NOTE:

  • Contract: Reflexive, Symmetric, Transitive, Consistent, and Non-nullity and It is consistent.
  • It is symmetric. For any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive. For any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true.
  • It is consistent. For any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals() comparisons on the object is modified.
  • For any non-null reference value x, x.equals(null) should return false.
Code Example
Output
this.class: class Car
obj.class: class Car
true

NOTE:

In String class .equals() method is overriden for content comparision, but not for reference comparison.