Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does every constructor in Java implicitly call Object's constructor?

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?

like image 897
nmeln Avatar asked Jul 01 '15 18:07

nmeln


1 Answers

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.

like image 54
rgettman Avatar answered Oct 12 '22 23:10

rgettman