Java – Why Multiple Calls to Same Class Constructor Fail

constructorsjavaobjectobject-oriented

Please have a look at following snippet:

public class Foo {
int digit;
String name;

Foo (int d, String n) {
    this(d);
    // cannot do following.
    //compile-time error: Constructor call must be first statement in a Constructor 
    //this(n);
}

Foo (int p) {
    digit = p;
}

Foo (String q) {
    name = q;
}

What would be the reason of this restriction? I understand why call to Constructor (both in a Constructor or in a method) has to be first statement – the object should be initialized properly before it is used. What I don't get is compiler not allowing calling multiple constructors of the same class from within a constructor. I don't see any problem with this construct – both regarding initialization and invarients.

It'd be great if someone can shed some light on what I am missing here…

Thanks!

Best Answer

Constructors are not just "methods that are called when object is created", they are conceptually different.

Constructor's purpose is to constrain what states objects can be in initially. A freshly created object is zeroed on all fields (null/0/false) and that may be an invalid state in your program. For example, a Customer object in your application needs be constrained to always have a customerId > 0 — you then define a constructor that takes that id and checks it.

In this light there is no purpose in calling two constructors: after calling the first one the object is already in a consistent state. The second constructor will receive an initialized object which is a breach of its purpose (doing 0 => initialized).

What you want to do in this case is either introduce private methods that will do parts of that initialization and call them or make more specific constructors call the more general one (which is a very common pattern):

Foo (int d, String n) {
    digit = d;
    name = n;
}

Foo (int p) {
    this(p, null)
}

Foo (String q) {
    this(0, q)
}