File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confusion with Constructor " Watch "Confusion with Constructor " New topic

Confusion with Constructor

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
class Tester {
int var;
Tester(double var) {
this.var = (int)var;
Tester(int var) {
Tester(String s) {
Tester() {
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()
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
I did not realize that this("hello") was calling the constructor with string arg.
Its clear to me now
I agree. Here's the link:
subject: Confusion with Constructor
It's not a secret anymore!