Object class Methods

Object class is the most important class in Java. It is present in java.lang package.

Object class is the parent class for almost all the class in java either directly or indirectly.

Object class by itself provides certain methods namely.

  1. tostring() method
  2. hashCode() method
  3. equals(Object obj) method
  4. finalize() method
  5. getClass() method
  6. clone() method
  7. wait(), notify() notifyAll() methods
You may wonder that some methods are used in Thread class, Map Interface etc are by default Object class's methods.
Each method has specific Functionality to perform which we will discuss here.

toString() Method

toString() method is used to convert the Object into String representation. By Default, it is always a good practise to override the toString() method to print the String Representation of the Object.

HashCode() Method

The JVM creates a hashcode, or distinct number, for each object. For different items, it returns different integers. It's a frequent misperception that this method's hashCode() call returns the object's address, but this is untrue. It applies an algorithm to transform the object's internal address to an integer.

Equals(Object obj) Method

It compares "this" item with the provided object (the object on which the method is called). It provides a general method to check whether two items are equal. For our own equality condition on Objects, it is advised to override the equals(Object obj) method.

Finalize() Method

Just before an object is garbage collected, this function is invoked. When the garbage collector judges that there are no more references to an item, it is referred to as the garbage collector. For system resource to reduce memory leaks, we should override the finalise() method.

getClass() Method

To determine the actual runtime class of the object, it returns the class object of "this" object. It can also be used to obtain this class's metadata. We don't override it because it is final.

Clone() Method

It returns an object that is exactly the same as the object which invoked the clone method.

Wait(), Notify() & NotifyAll() Method

Wait() is called for a thread to pause it operation and wait for a certain time period or until an another thread which occupied the monitor to call Notify() or NotifyAll() method.
These methods are used in the Concurrency Control.

Comments

Popular posts from this blog

Why Pointers are Eliminated in Java?

What is the advancement made in Hashmap in Java 8?

Integer.parseInt(“text”)