1

why this() needs to be in the first statement of constructor-chaining?

why multiple this() with different argument doesn't work in the final Constructor?

package thislatest;

public class ThisLatest {

    public static void main(String[] args) {
            A a1= new A(10,20,30);
            a1.display();
    }

}

class A
{
    int x,b;
    static int c;
    A(){ System.out.println("constructor chaining1");}

    A(int y)
     {   //this();
         System.out.println("constructor chaining2");
         b=y; 
     }

    A(int x,int y)
     {
        // this(x);
         System.out.println("constructor chaining3");
         x=x;
         x=y;
     }

       A(int x,int y,int c)
     {   this();
         this(y);
         this(x,y);
         x=x;               //self reference initialised by previous constructor
         b=y;               //no need of this keyword since name is different
         this.c=c;         //current instance variable  or A.c=c will also work
     }

     void display()

     {
        System.out.println(x+b);            //wrong result due to self reference
        System.out.println(c+b);            //correct reference
     }

}

why can't I use multiple this() in the constructor A(int x,int y,int c)?

Why this needs to be the first statement?

Is it just to maintain a flow of language?

I am a beginner please use simple terms :)

ekaf
  • 153
  • 2
  • 13
  • 2
    well read this http://stackoverflow.com/questions/1168345/why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor?rq=1 – Bibek Shakya Aug 21 '16 at 12:47
  • i do read stackoverflow answer before asking same type of question. i didn't understand those answer – ekaf Aug 21 '16 at 12:49
  • You can do that with private initializer methods without side effects. But if you ask for Constructor, you should think in the final field, if you initialize this final fields with many constructors, a final field can be initialized some times, and this is a problem. – David Pérez Cabrera Aug 21 '16 at 12:51

3 Answers3

1

You are not allowed to call upon multiple constructors in the same constructor, but you are allowed to chain them so that one calls another and so on. You can do this until you run out of constructors in your class. Consider the class below:

public class MyClass() {
    public MyClass() {
        this(1);
        System.out.printf("Calling MyClass()%n");
    }

    public MyClass(int a) {
        this(a, 2);
        System.out.printf("Calling MyClass(%d)%n", a);
    }

    public MyClass(int a, int b) {
        System.out.printf("Calling MyClass(%d, %d)%n", a, b);
    }
}

And the following client code:

public class Client() {
    public static void main(String[] args) {
        new MyClass();
    }
}

The output if you ran the code above would be:

Calling MyClass(1, 2)
Calling MyClass(1)
Calling MyClass()

The order of the output above appears to be in the wrong order because the printf() calls are done after the constructor calls. By following the arrows below, you can see where the constructor calls begin, and where it finally ends:

Object        MyClass               Client
------        -------               ------
              MyClass() <---------- main(String[])
                 |
                 V
              MyClass(int)
                 |
                 V
Object() <--- MyClass(int, int)

If you wonder what the last arrow means: All Java-classes, including MyClass, secretly extend the Object-class. The last constructor in MyClass actually looks like this:

    public MyClass(int a, int b) {
        super();
        System.out.printf("Calling MyClass(%d, %d)%n", a, b);
    }

Your class needs at least one constructor that calls super() implicitly or explicitly, otherwise the constructor chain would be stuck in a loop. The compiler gives you an error if that happens.

Thomas Kåsene
  • 5,301
  • 3
  • 18
  • 30
0

Each constructor initializes a single instance of a class. Thus in a constructor you can only invoke one other constructor. The reason that constructor invocation has to be the first one is to say that you delegate the creation of an instance to another constructor. Otherwise if the first line of your constructor is not an invocation of another constructor the instance is instantiated already before the first line executed (i.e. super() is invoked implicitly). Thus calling constructor after is like calling some constructor within your constructor second time, which obviously will be illegal as constructor instantiates one instance only

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
0

why this() needs to be in the first statement of constructor-chaining?: because it is required by Java specs! Python for example allows programmer to call superclass initialization method anywhere. But Java do not allow it. Full stop.

why multiple this() with different argument doesn't work in the final Constructor? same answer as above. It is useless to ask why, just think of how because you will not change the language specs.

So let us think about the how. You may have good reasons to call an initialization method not as the first instruction of a constructor. In that case, just use non constructor initialization methods, and call those methods from constructors:

class A {
    private void init1(int x) {
        // do something with x
    }

    private void init2(int x, int y) {
        // do something with x and y
        ...
        init1(x); // eventually call init1 in the middle of init2
        ...
    }

    A(int x) {
        y = 2 *x + 1;
        init2(x, y);    // call initialization method in the middle of ctor
    }
    A(int x,int y) {
        // eventually some instructions
        init2(x, y);
        // eventually other instructions
    }
}

In Java language, constructors are special. You will have to use another language if you cannot accept it.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252