Skip to content
Advertisement

How is a constructor executed?

I am making some revisions from the lecture slides and it says a constructor is executed in the following way:

  1. If the constructor starts with this, recursively execute the indicated constructor, then go to step 4.

  2. Invoke the explicitly or implicitly indicated superclass constructor (unless this class is java.lang.Object).

  3. Initialise the fields of the object in the order in which they were declared in this class.

  4. Execute the rest of the body of this constructor.

What I don’t understand is that a constructor can never “start” with this, because even if it forms no class hierarchy/relationship then super() is inserted by default.

How would this fit in with the description above?

Advertisement

Answer

A constructor (for every class except java.lang.Object) has to start with either “super()”, to call its superclass’ constructor, or “this()”, to call another constructor of the same class. If you don’t include either of those in your constructor the compiler will insert a call to super(). It’s fine for a constructor to start with a call to another constructor in the same class, as long as eventually a constructor in the class gets called that calls a superclass constructor.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement