views:

186

answers:

3

I am doing some reviison 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 dont undertsand is that, a constructor can never "start" with this, because even if it forms no class heirarchy/relationship then super() is inserted by default.

How would this fit in with the description above?

Thanks

+7  A: 

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.

Nathan Hughes
+2  A: 

I don't think you're right, or I don't understand the problem. From the Java Language Spec:

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 is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

As such a constructor can start with this(...) which calls another constructor of the same class. Only when a constructor is called which does not start with either this(...) or super(...), super() is called automatically.

What I would say is that after an object is constructed super(...) has been called (if the class is not java.lang.Object).

extraneon
+2  A: 

here a more or less practical example for using this(...)

public class Car {

    private final int numberOfDoors;

    public Car(int doors) {
        numberOfDoors = doors;
    }

    public Car() {
        this(4);    // default is 4 doors, calls the constructor above
    }
}
Carlos Heuberger