![]() |
VOOZH | about |
Object class (in Java.lang) is the root of the Java class hierarchy. Every class in Java either directly or indirectly extends Object. It provides essential methods like toString(), equals(), hashCode(), clone() and several others that support object comparison, hashing, debugging, cloning and synchronization.
Example: Using toString() and hashCode()
Person{name:'Geek'}
321001045
Explanation: In the above example, we override the toString() method to provide a custom string representation of the Person class and use the hashCode() method to display the default hash code value of the object.
Object class provides multiple methods which are as follows:
👁 Object Class Methods in JavatoString() provides a String representation of an object and is used to convert an object to a String.
Student{name='Vishnu', age=21}
Explanation: Overridden toString() prints a custom readable string for the object
hashCode() method returns the hash value of an object (not its memory address). Used heavily in hash-based collections like HashMap, HashSet, etc.
3131
Explanation: hashCode() returns an integer value used in hashing-based collections like HashMap. If two objects are equal, they must produce the same hash code.
equals()method compares the given object with the current object. It is recommended to override this method to define custom equality conditions.
true
Explanation: equals() compares objects based on content rather than reference. Must be overridden when custom comparison logic is needed.
getClass() method returns the class object of "this" object and is used to get the actual runtime class of the object.
Class of Object o is: java.lang.String
Explanation: The getClass() method is used to print the runtime class of the "o" object.
finalize() method is invoked by the Garbage Collector just before an object is destroyed. It runs when the object has no remaining references. You can override finalize() to release system resources and perform clean up, but its use is discouraged in modern Java.
1510467688 end finalize method called
Explanation: The finalize() method is called just before the object is garbage collected.
clone() method creates and returns a new object that is a copy of the current object.
Vishnu Vishnu
Explanation: clone() creates a copy of the current object (shallow copy by default). Class must implement Cloneable or else it throws CloneNotSupportedException.
These methods are related to thread Communication in Java. They are used to make threads wait or notify others in concurrent programming.
The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979) The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979) b1 equals b2: true b1 hash code: 1840214527 b2 hash code: 1840214527
Explanation: The above example demonstrates the use of toString(), equals(), hashCode() and clone() methods in the Book class.