The Object class in Java is the superclass of all classes in the Java language. It is the root of the class hierarchy. Every class in Java is a subclass, directly or indirectly, of the Object class. This means that every class in Java has the methods and fields defined in the Object class.
The Object class is defined in the java.lang
package, which is automatically imported into all Java programs. This means that we don’t have to import the Object class or the java.lang
package in our Java programs.
The Object class has several methods that are defined in it. Some of the important methods of the Object class are:
toString()
: This method returns a string representation of the object. The toString() method is defined in the Object class and is inherited by all subclasses. By default, the toString() method returns the name of the class of the object followed by its hashcode, which is a unique identifier for the object.equals()
: This method compares the given object with the current object and returns true if they are equal, and false otherwise. The equals() method is defined in the Object class and is inherited by all subclasses. By default, the equals() method compares the memory addresses of the objects, which means that two objects are equal only if they are the same object.hashCode()
: This method returns a hashcode for the object. The hashcode is a unique identifier for the object. The hashCode() method is defined in the Object class and is inherited by all subclasses.clone()
: This method creates a copy of the object. The clone() method is defined in the Object class and is inherited by all subclasses. By default, the clone() method creates a shallow copy of the object, which means that it only copies the fields of the object and not the objects referenced by the fields.finalize()
: This method is called by the garbage collector before it reclaims the memory used by the object. The finalize() method is defined in the Object class and is inherited by all subclasses.
In addition to the methods mentioned above, the Object class also has several fields, such as the class
field, which holds the Class
object for the class of the object.
Conclusion
The Object class is the superclass of all classes in the Java language and has several important methods and fields that are inherited by all subclasses. It is an essential part of the Java language and is used in almost all Java programs.