Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes not extending java.lang.Object

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?

like image 997
Ajay Avatar asked Dec 04 '22 14:12

Ajay


1 Answers

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.

like image 149
David Z Avatar answered Dec 28 '22 17:12

David Z