The Universal Super class - the Object Class


The Universal super class in java - The Object Class, why object class is known as Universal super class, what are key features in it

The Object Class is known as universal super class of Java. This is so because Every class you create in Java automatically inherits the Object class. The Object class is super class of all the classes in Java either directly or Indirectly. You don't need to extend it manually. All the properties of Object class are already in your class.

You can find the definition of the Object class in java.lang package And there are a few useful methods in this class which you can override in your class. Following program shows a few method with the examples.


public class ObjectClass {
    public static void main(String[] args){
        ObjectClass oc = new ObjectClass();
        System.out.println(oc.hashCode());
        System.out.println(oc.toString());
        System.out.println(oc.getClass());
        
        ObjectClass oc1 = new ObjectClass();
        System.out.println(oc.equals(oc1));
        System.out.println(oc1.hashCode());
        System.out.println(oc1.toString());
        
        ObjectClass oc2 = oc;
        System.out.println(oc.equals(oc2));
    }
}

the output is

1680090029
ObjectClass@642423ad
class ObjectClass
false
1386102722
ObjectClass@529e3fc2
true

 

Note: the output could be slightly different when you run this program because its up to JVM what hash code it generates for object on your system.

In the output you will see that when I used the equals() to compare two object of same class oc and oc1 it returns false, this is because every Object has a different hash code, as you can see in the next like of the boolean result. shows that its is a different object. However if you try to match an object with its reference it will always return the true.

I guess there is no need to explain every single bit in the program but here is a small overview of all the methods I have used in this small program.

hasCode() - this returns the hash code associated with the Object
toString() - returns any object in the form of string
getClass() - returns the class Name of the Object
equals() - check if two objects are equal or not.

along with these main and commonly used methods there is another one which is less used but is very useful and powerful. clone() this is used to clone the object.

NOTE: If you have JDK installed you may check the complete definition of Object using command: javap java.lang.Object.