According to the Java Language Specification, java.lang.Object is the root of Java's inheritance hierarchy. Unlike C++ or Objective-C, programmers cannot specify their own root superclasses. Because of this, I figured it was impossible to actually define java.lang.Object in Java itself. To my surprise, I found that OpenJDK indeed has a concrete implementation of java.lang.Object.
I wanted to see if it was possible to compile and run my own version of java.lang.Object with JDK/JRE 1.8, so I wrote this as Object.java:
package java.lang;
public class Object {
public static void main(String[] args) {
System.out.println("Hello world from custom java.lang.Object!");
}
}
It compiled just fine with javac, but if I try to execute the classfile via java -cp . java.lang.Object, the JVM errors out with this message:
Error: Main method not found in class java.lang.Object, please define the main method as:
public static void main(String[] args)
which suggests that the JVM is using the stock java.lang.Object instead of the Object.class in the classpath.
Is it possible to define java.lang.Object in Java as an end user? What is going on under the hood? I see two possibilities:
- The JVM loads a real
Object.classfile that was compiled from the OpenJDK'sObject.java. If this is the case, does the compiler do something special to prevent the classfile from specifying itself as the superclass? java.lang.Object's implementation is intrinsic to the JVM. If this is the case, why is there anObject.javain OpenJDK?