Introduction
In Java, the Object
class is the root class for all classes. Every class in Java is implicitly or explicitly a subclass of Object
. It provides some common methods that can be used by all objects in Java.
Common Methods in Object Class
toString()
Method:
- The
toString()
method returns a string representation of the object. - The default implementation in the
Object
class returns a string consisting of the class name followed by the “@” character and the object’s hashcode.
equals(Object obj)
Method:
- The
equals()
method is used to compare the equality of two objects. - By default, it compares the memory addresses of the two objects. However, it is often overridden in user-defined classes to compare the contents.
hashCode()
Method:
- The
hashCode()
method returns a hash code value for the object. - This method is often overridden in user-defined classes for better hash code computation.
getClass()
Method:
- The
getClass()
method returns the runtime class of an object.
Overriding toString()
, equals()
, and hashCode()
It’s common to override these methods in your custom classes to provide meaningful implementations for your objects. Here’s an example:
Conclusion
Understanding the Object
class and its methods is essential when working with Java, as it provides a foundation for object-oriented programming in the language. By overriding methods like toString()
, equals()
, and hashCode()
, you can customize the behavior of your classes to suit your specific needs.