Object Class in Java
Object Class in Java
Every class in Java is directly or indirectly derived from the Object class.
If a Class does not extend any other class then it is direct child class
of Object and if extends other class then it is an indirectly derived.
Therefore the Object class methods are available to all Java classes.
The default toString() method for class Object returns a string consisting of the name
of the class of which the object is an instance, the at-sign character `@’, and the
unsigned hexadecimal representation of the hash code of the object.
Example
public String toString()
{
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Note : Whenever we try to print any Object reference, then internally toString() method is called.
Student s = new Student(); // Below two statements are equivalent
System.out.println(s);
System.out.println(s.toString());
hashCode() : For every object, JVM generates a unique number which is
hashcode.
JVM(Java Virtual Machine) uses hashcode method while saving objects into
hashing related data structures like HashSet, HashMap, Hashtable etc.
The main advantage of saving objects based on hash code is that searching
becomes easy.
Note : Override of hashCode() method needs to be done such that for every
object we generate a unique number.
equals(Object obj) :
Compares the given object to “this” object (the object on which the method is
called).
getClass() : Returns the class object of “this” object and used to get actual
runtime class of the object.
The returned Class object is the object that is locked by static synchronized
methods of the represented class.
Note :finalize method is called just once on an object even though that object
is eligible for garbage collection multiple times.
clone() : It returns a new object that is exactly the same as this object. For
clone() method refer Clone()