user2655970
user2655970

Reputation: 123

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

Upvotes: 0

Views: 105

Answers (3)

JLRishe
JLRishe

Reputation: 101680

Edit Eric pointed out the actual issue, which is that you are printing out this.s after it has only been modified once. Also as he says, if you had += in all the right places, they would be concatenated in the opposite order of what you are expecting.

Note that there is a major problem with these constructors in that if you use any one other than the first, it will error out due to a null reference. You should have:

if(this.s == null){
   this.s = "";
}

at the beginning of all the constructors except the first.

Upvotes: 1

Chris Bode
Chris Bode

Reputation: 1265

You're only seeing Fifth because your System.out.println() call is right after this.s = "Fifth";

If you add a System.out.println after every addition to s, you get:

Fifth
FifthFourth
FifthFourthThird
FifthFourthThirdSecond
First

First resets it because you used = there instead of +=. Fix that, and you get:

Fifth
FifthFourth
FifthFourthThird
FifthFourthThirdSecond
FifthFourthThirdSecondFirst

Upvotes: 0

Cat
Cat

Reputation: 67502

You're right and wrong.

The remaining code in the other constructors does execute, but you print out the value of this.s before they do.

Here is the flow of your code, in vertical chronological order:

parent()
  this(10)
    this(10.00f)
      this("sss")
        this('a')
          this.s = "Fifth"
          System.out.println(this.s)
        this.s += "Fourth"
      this.s += "Third"
    this.s += "Second"
  this.s = "First"

You'll either need to print out p.s after new parent(), or move your print statement to the end of parent() (and change = "First" to += "First").

Upvotes: 4

Related Questions