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 :)
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.