Object Class in Java | Methods, Example

Object class is the superclass of all the classes in Java by default. It is present with a name “Object” in java.lang package.

The java.lang.Object class is the root of the Java class hierarchy. It is the topmost class of all java classes, including your classes as well.

Every class in Java is derived from java.lang.Object class. In other words, every class is a direct or indirect subclass of Object class.

When we define a class in Java without specifying inheritance, the superclass (i.e. parent class) of the class is Object class by default.

For example, the following two class declarations are the same:

Object class in Java with example

Classes like String, StringBuffer, StringBuilder, including your defined class, etc are implicitly subclasses of Object class by default.

Java Object class declaration


The general syntax to declare an Object class in Java is as:

public class Object

This Object class was added to JDK 1.0.

Advantage of Object class


The reference of Object class can store any reference of any object. This becomes an advantage when we want to refer to any object unknown type. Consider the following example to understand better.

1. Super class reference variable can refer to sub class object, know as upcasting in Java.

2. We use getClass() method to determine the class of an object reference in a superclass variable. It is useful because a parent class reference variable can hold references to objects of any of its child classes.

3. We use getObject() method that returns an object. But the returned object can be of any type, like Collage, Student, Employee, etc. We can use Object class reference to refer to that object. For example:

Object obj = getObject(); // Here, we don't know what type of object will return from this method.

Object class Methods in Java with Example


Object class in Java provides some useful methods to compare objects, to create a clone of object, to convert an object into a string, to notify the threads (processes), etc.

Every class is an implicit subclass of Object class and can implement its methods. Here are some of the common useful methods of Object class that are as:

  • equals()
  • getClass()
  • toString()
  • hashCode()
  • finalize()
  • clone()
  • notify()
  • notifyAll()
  • wait()

1. equals(): If you want to compare the references of two objects, use equals() method of Object class. This method compares the references of two objects.

It returns true if the object invoking equals() method is equal to the object passed as an argument to the equals() method, otherwise returns false.

The general signature of this method is as:

public boolean equals(Object obj)

This method evaluates whether two objects are equal. The syntax for calling it is:

object1.equals(object2);

The default implementation of the equals() method in the Object class is as:

public boolean equals(Object obj) {
  return (this == obj);
}

This implementation tests whether two reference variables points to the same object using double equal operator (==). We can override this method in a user defined class to check whether two distinct objects have the same content.

For example, the equals() method of String class is inherited from the Object class and is modified in String class to check whether two strings are identical in content.

Example Program: equals() Method of Object class


Let’s create a Java program to compare two objects by using equals() method of Object class. This method normally compares the references of two objects. If both references points to the identical objects, then it gives true, otherwise it gives false.

But in the case of String objects and wrapper class objects (Character, Integer, Long, Float, etc. are wrapper classes), it compares the content of the objects. If the contents are identical, then it gives true. Otherwise, it gives false.

In this example program, we are using equals() method to compare two objects of a user defined class named “Myclass”. We will also compare two objects of wrapper class “Integer”.

In case of Myclass objects, if the references are identical, it returns true, else, returns false. In case of Integer class objects, equals() method returns true if contents are the same, otherwise false.

Program code 1:

// Here, equals() method takes Myclass to store an int value.
public class Myclass {
 int x;
 Myclass(int x) {
  this.x = x;
 }
}
public class Compare {
public static void main(String[] args) 
{
// Create two Myclass objects having the same content.
// In this case, references of both objects will be different.
   Myclass obj1 = new Myclass(20);
   Myclass obj2 = new Myclass(20);
// Checking for equality of objects.
   if(obj1.equals(obj2)) {
	  System.out.println("obj1 and obj2 are same"); 
   } else {
	  System.out.println("obj1 and obj2 are not same"); 
   }
// Create two wrapper class objects and store the same content.
// In this case, references of both objects will be different.
   Integer obj3 = new Integer(20);
   Integer obj4 = new Integer(20);
// Checking for equality of contents.
   if(obj3.equals(obj4)) {
	 System.out.println("obj3 and obj4 are same");  
   } else {
	  System.out.println("obj3 and obj4 are not same"); 
   }
  }
}

When you will run this program, you will get the following output:

Output:
      obj1 and obj2 are not same
      obj3 and obj4 are same

2. getClass(): This method returns an object containing the name of a class to which an object belongs. In other words, it gives the runtime class of an object. The general signature of this method is as:

Class<? extends Object> getClass()

Example Program: getClass() Method of Object class


Let’s take an example in which we will use getClass() method of Object class to know the name of class to which an object belongs.

Program code 2:

package javaProgram;
public class Myclass {
 int x;
 Myclass(int x) {
  this.x = x;
 }
 static void printName(Object obj) 
{
// Getting the name of class into an object c of the class Class.
   Class c = obj.getClass();
// Retrieving the name of class using getName.
   String name = c.getName();
   System.out.println("Name of class: " +name);
 }
}
package javaProgram;
public class Demo {
public static void main(String[] args) 
{
// Create an object of class Myclass.
   Myclass obj = new Myclass(20);
// Calling printName() to know the name of class of the object obj.   
   obj.printName(obj);
  }
}
Output:
      Name of class: javaProgram.Myclass

In this example, getClass() method gets the class name of the object and stores it into an Object class reference variable c. Using c.getName() method, we can get the name of class.


3. toString(): This method gives a string representation of an object. For example, the string representation of an Integer object is an integer number printed as a string. The general signature of this method is:

public String toString()

Let’s understand it with the help of an example program.

Program code 3:

package javaProgram;
public class ToStringExample {	
 public static void main(String[] args) 
 {
// Create a Integer class object.
   Integer obj = new Integer(234);
   String str = obj.toString();
   System.out.println("Srting representation: " +str);
   System.out.println(str + 567);
   System.out.println("Integer number: " + (obj + 567));
 }
}
Output:
      Srting representation: 234
      234567
      Integer number: 801

4. hashCode(): This method returns a hash code value of an object. The general signature of this method is as:

public int hashCode()

Example Program: Find a hash code value for an object


Let us take an example program on it.

Program code 4:

public class HashCodeExample {	
 public static void main(String[] args) 
 {
// Create a Integer class object.
   Integer obj = new Integer(10);
// Call hashCode() method to get hash code value. 
   int getValue = obj.hashCode();
   System.out.println(getValue);
 }
}
Output:
      10

5. finalize(): Garbage collector calls this method when an object is removed from the memory. In other words, the finalize() method is called by garbage collector on an object when there are no more references to an object. The general signature of this method is as:

protected void finalize() throws Throwable

For more detail about this method, go to this tutorial: Object finalization in Java


6. clone(): This method creates and returns an exact copy (clone) of an existing object. The general signature of clone() method is as:

protected Object clone() throws CloneNotSupportedException

We will understand more about it in the next tutorial.


7. notify(): This method wakes up a single thread that is waiting for a particular object. It sends a notification for only one thread at a time.

If multiple threads are waiting for the notification, only one thread receives the notification by notify() method and wakes up. The remaining threads will have to wait for further notification. The general signature of notify() method is:

public final void notify()

This method does not return any value.


8. notifyAll(): This method wakes up all threads that are waiting for an object. It sends the notification for all threads at a time. The general signature of notifyAll() method is as:

public void notifyAll()

9. wait(): This method causes the current thread to wait until another thread calls notify() or notifyAll() method for this object. The general syntax of wait() method is:

public void wait()

This method returns nothing.


10. wait(long timeout): This method causes the current thread to wait for the specified milliseconds until another thread notifies or calls notify() or notifyAll() method for this object. The general syntax for this method is as:

public void wait(long timeout)

This method does not return anything.


11. wait(long timeout, int nanos): This method causes the current thread to wait for the specified milliseconds and nanoseconds until another thread notifies or calls notify() or notifyAll() method for this object. The general signature is:

public void wait(long timeout, int nanos)

This overloaded wait() method returns nothing.


In this tutorial, you learned Object class in Java and its important defined methods with example programs. Hope that you will have understood the basic points of Object class and practiced all programs.
Thanks for reading!!!