Saturday, January 11, 2020

The Object Class in Java

The Object Class

The object class is the root of the class hierarchy. Every user-defined class directly or indirectly extends Object class. Variable of type object can refer to any Object. The Object class can not hold primitive data types like int, float, boolean, etc. but if required objects of wrapper classes like Integer, Float, Boolean, etc. can be used.

The object class defines a number of methods that are inherited by all objects. These methods fall into two categories,
  • General utility methods
  • Methods to Support Threads
Object class and methods java
Object class and methods

General utility methods

  • public boolean equals(Object object)
  • public int hashCode()
  • protected Object clone()
  • protected void finalize() throws Throwable
  • public String toString()

 public boolean equals(Object obj)

This method compares the receiving object and the object referenced by obj for equality. This method returns true if they have the same value and false if they don't. To determine the equality of reference, if both compared objects refer to the same object, you can use == or != operators. The equals() method is concerned with value equality, not the references. The default implementation of equals() in Object class is equal to itself only.

 
 public int hashCode()

This method returns the hash code of this object. Each object has some hash code for the use of hash tables. The default implementation returns a value that is different for each object. This value is used when we store these objects in hash Hashed collections like HashTable, HashMap, etc.

 protected Object clone()

This method returns the clone of this object if the Class of the object implements the Cloneable interface. The cloned object is a new copy of this object itself.
The clone() method throws CloneNotSupportedException.

 protected void finalize() throws Throwable

 This method finalizes the object during garbage collection. This method returns Throwable

 
 public String toString()

This method returns the String representation of the object. This method is implicitly invoked whenever an object reference is used within a string concatenation expression as an operand of the + operator. The Object version of toString() constructs a string containing the objects class name, @ character and hexadecimal representation of hash code of the object, all three concatenated.


Video Tutorial