While you create a user defined class in Java, you do not specify it as extending Object. But still the class is an Object. How does this work? How does javac or the JVM inject all properties of a class to the user defined class?
All java classes implicitly extend java.lang.Object. From the documentation:
Class Object
is the root of the class hierarchy. Every class has Object
as a superclass. All objects, including arrays, implement the methods of this class.
Here's a link to JVM spec as well:
The standard class Object
is the superclass (§2.8.3) of all other classes. A variable of type Object
can hold a reference to any object, whether it is an instance of a class or an array. All class and array types inherit the methods of class Object.
If you don't actually write extends Object
, the compiler inserts it for you.
EDIT: Apparently I caused some confusion about whether there is actually an insertion of code going on. I wasn't entirely sure myself so I ran a little experiment: create the following class in file test.java
:
public class test {}
and compile it, then run
javap -c test
to disassemble the bytecode. Look what comes out:
Compiled from "test.java" public class test extends java.lang.Object{ public test(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."":()V 4: return }
So yes, the compiler does actually insert extends java.lang.Object
(or the bytecode equivalent) into the class.
Well, this may be a glib answer (my favorite kind), but it probably does it the same way it derives a class if you specify a parent. Isn't that how you'd do it if you were writing the compiler?
To say that the JVM "injects" properties or methods into the class makes it sound like it's something the compiler or runtime does after the fact, as though the .class file is different. Really, all that happens is that when the parser sees that you haven't included any base class with extends
, it simply pretends you explicitly specified Object
. From that point onward, the compiler treats it the same as if you'd typed it out yourself, and the JVM hasn't a clue what you did or didn't specify in the source code.