Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Object superclass

Tags:

java

I have a weird Java question:

As we know:

  1. All Java classes extend java.lang.Object
  2. All Java classes cannot extend itself

Then, java.lang.Object must extend java.lang.Object, which is itself, therefore, it should be impossible. How is Object implemented in Java?

like image 588
Ming-Tang Avatar asked Apr 24 '10 20:04

Ming-Tang


2 Answers

Object is an exception to the first rule, and has no superclass. From JLS3 8.1.4:

The extends clause must not appear in the definition of the class Object, because it is the primordial class and has no direct superclass.

You can also try it out with reflection:

Object.class.getSuperclass(); // returns null
like image 63
Michael Mrozek Avatar answered Oct 08 '22 14:10

Michael Mrozek


You'd be better off thinking of this as:

  1. All java classes must implement the interface implied by the methods in java.lang.Object.
  2. The concrete class java.lang.Object provides default implementations of these functions.
  3. All other java classes are derived from the object java.lang.Object and may choose to use or override the default implementations of the methods.

The two main points are: all the classes must implement the implied interface and the Java language spec gives you (forces upon you?) default implementations for these methods for free.

like image 40
Tim Perry Avatar answered Oct 08 '22 14:10

Tim Perry