Java - Class Object Class

What is Object class?

Java has an Object class in the java.lang package.

All Java classes extend the Object class directly or indirectly.

Object class is the superclass of all classes.

Object class is at the root of class hierarchy.

Rule

  • A reference variable of the Object class can hold a reference of an object of any class.
  • The Object class's nine methods are available to be used in all classes.

Example

For the obj variable whose type is Object

Object obj;

You can assign a reference of any object in Java to obj.

assign the null reference

obj = null;

assign a reference of an object of the Object class

obj = new Object();

Can assign a reference of an object of the Account class

Account act = new Account();
obj = act;

Cast

The following code tries to assign the same reference back to a reference variable of the Account type.

Object obj2 = new Account();
Account act = (Account)obj2; // Must use a cast

Related Topics

Exercise