10

I know that if class does not extend any other class, then it implicitly extends Object class.

Does this mean that when I call my class constructor, the base class Object's constructor is called as well?

Does Object even have a constructor?

0

1 Answer 1

12

Yes, every superclass's constructor must be called, explicitly or implicitly, all the way up to Object. Each class must construct its part of the object, including Object.

The JLS, Section 8.8.7, states:

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

Each constructor calls its direct superclass constructor, which calls its direct superclass constructor, until Object's constructor is called.

But what if you don't declare a constructor at all in a class? The default constructor is implicitly created, according to the JLS, Section 8.8.9:

If a class contains no constructor declarations, then a default constructor is implicitly declared.

and

If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

Either way, the superclass constructors will get called all the way up to Object.

The compiler, not the JVM, inserts the implicit call to the superclass constructor. With a do-nothing class that has no explicit constructor:

public class DoNothing {}

This is the bytecode:

$javap -c DoNothing.class
Compiled from "Main.java"
class DoNothing {
  DoNothing();
    Code:
       0: aload_0
       1: invokespecial #1         // Method java/lang/Object."<init>":()V
       4: return
}

The call to Object's constructor is explicit in the byte code.

Sign up to request clarification or add additional context in comments.

3 Comments

Fun fact: the JVM does not require this.
Is this handled by the compiler or the JVM when it interprets the bytecode?
@JamesWierzba The compiler. See my amended answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.