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