Object Class in Java

The Object class is the main parent class in Java. All classes indirectly inherit the Object class. That said, all classes are instances of the Object class.

See the following example:

class Vehicle {
  // ...
}
class Car extends Vehicle {
  // ...
}
class Test {
    
  public static void main(String[] args) {
    Vehicle vehicle = new Vehicle();
    Car car = new Car();

    System.out.println(vehicle instanceof Object);
    System.out.println(car instanceof Vehicle);
    System.out.println(car instanceof Car);
  }
}
Output: true true true
 
As you can see, the Vehicle class inherited by the Car class is an instance of the Object class, just as the Car class is an instance of both the Vehicle and the Object class.

All classes in Java inherit some very useful methods from the Object class:

Methods that Other Classes Inherit from the Object Class

Method Description
public final Class getClass() returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object.
public String toString() returns the string representation of this object.
public final void notify() wakes up the single thread, waiting on this object’s monitor.
public final void notifyAll() wakes up all the threads, waiting on this object’s monitor.
public final void wait() throws InterruptedException Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
public final void wait(long timeout) throws InterruptedException 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.
public final void wait(long timeout, int nanos) throws InterruptedException 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.
protected void finalize() throws Throwable Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.


That’s it!

 

Leave a Reply

Your email address will not be published.