Javatpoint Logo
Javatpoint Logo

Cosmic Superclass in Java

In Java, the Object class is the parent class of all the Java classes. Every Java class is a direct or indirect child of the Java Object class. Hence, every Java class extends the Object class. Therefore, we need not to write the following statement to inherit the class.

The subclass internally inherits all the methods of the Object class. Hence, we can say that the Object class is the cosmic superclass in Java. The class belongs to java.lang package.

Java Object Class: The Cosmic Superclass

  • Variable of type Object could be used to refer to objects of any type.
  • The equals() method of the Object class tests whether two objects point to the same memory.
  • Override equals() method if we want to define our own equality of object.
  • Override toString() method for printed representation of the class.
  • Whenever an object is concatenated to String using the "+" operator, the Java compiler invokes the toString() method.
  • The Object class defines the toString() to print the class name and the memory location of an object.
  • The toString() method is a great debugging tool for traces.

The Object class can be used if we want to refer to any object whose type is unknown. Note that the parent class reference variable can refer to the child class object, the mechanism is known as upcasting.

The Object class provides methods for some common behaviors to all the objects such as comparing two objects, create a clone of an object, the object can be notified, etc.

The four most important methods of the cosmic superclass (Object class) are as follows:

Methods Description
String toString() It returns a string representation of the object.
boolean equals(Object obj) It checks the equality of objects. Note that the method does not compare the content of two objects instead it compares the references of two variables.
Object clone() It creates a copy of an object.
int hashCode() It returns an integer from the entire integer range.

Let's see an example.

ObjectComparison.java

Output:

false
false
true

In the above program, observe that we have not extended the Java Object class but used the equals() method of the Object class.

Let's see another example.

ToStringExample.java

Output:

The sum of integers is: 
The sum is: 150
ToStringExample@490d6c15

In the above example also, we have used the toString() method of the Object class without extending the class.

Therefore, the Java Object class is known as a cosmic superclass.


Next TopicShallow Copy Java





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA