• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusion with Constructor

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Tester {
int var;
Tester(double var) {
this.var = (int)var;
}
Tester(int var) {
this("hello");
}
Tester(String s) {
this();
System.out.println(s);
}
Tester() {
System.out.println("good-bye");
}
public static void main(String args[]) {
Tester t = new Tester(9);
}
}
While running this code, it prints out "good-bye" followed by "hello". I am not able to understand this. Could anyone throw some light on this, Thanks, Raj
 
Paul Smiley
Ranch Hand
Posts: 244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just follow it closely:
order executed:
1 Tester(int var) { //called with integer literal 9
2 this("hello"); //calls Tester(String s)
}
3 Tester(String s) { // called with "hello"
4 this(); // temporarily leaves this ctor and goes to no arg ctor
7 System.out.println(s); //returns from no arg and prints "hello"
}
5 Tester() { // called by this() within Tester(String s)
6 System.out.println("good-bye"); //prints out "good-bye" and returns to Tester(String s) following this()
}
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks,
I did not realize that this("hello") was calling the constructor with string arg.
Its clear to me now
-Raj
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic