File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confusion with Constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confusion with Constructor " Watch "Confusion with Constructor " New topic
Author

Confusion with Constructor

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Jun 02, 2000
Posts: 244
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

Joined: Nov 22, 2008
Posts: 18944
Thanks,
I did not realize that this("hello") was calling the constructor with string arg.
Its clear to me now
-Raj
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confusion with Constructor