简体   繁体   中英

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?

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.

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.

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?

这是因为所有用户定义的类型都隐式地从Object继承。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM