Saturday, 31 August 2013

Constructors overloading in Java

Constructors overloading in Java

class parent {
String s;
parent() {
this(10);
this.s = "First";
}
parent(int a){
this(10.00f);
this.s += "Second";
}
parent(float b){
this("sss");
this.s += "Third";
}
parent(String c){
this('a');
this.s += "Fourth";
}
parent(char d){
this.s = "Fifth";
System.out.println(this.s);
}
}
class chain {
static public void main(String[] string) {
parent p = new parent();
}
}
The output is
Fifth
I expected the following would be the flow
parent()->parent(int a)->parent(float b)->parent(String c)->parent(char d).
This happens but once the last constructor is executed I thought the
remaining String, float, int and no-arg constructor variants would be
executed because they do have code to process and is it not how they work.
I assume that constructors' execution is stack based (correct me if I am
wrong).

No comments:

Post a Comment