user5037864
user5037864

Reputation:

How do all classes inherit from Object?

All classes inherit from java.lang.Object, although extends Object is (generally) not written out anywhere. How is this possible?

Upvotes: 5

Views: 7665

Answers (2)

Razib
Razib

Reputation: 11163

The Object is implicitly direct/indirect super class of all class.

From Oracle Java doc:

Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).

Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.

Upvotes: 6

user4341816
user4341816

Reputation:

if you don't explicitly write extends Object the compiler does it for you. So knowing that a class can only extend one super class, the compiler will look at the hierarchy and extend the highest super class to Object. So every class will directly or indirectly inherit the Object class.

The Object class however is a special case because it doesn't extend anything.

Lastly if you were to compile a simple class and decompile it, you will see the compiler inserts extends java.lang.Object (or the bytecode equivalent) into the class

Upvotes: 26

Related Questions