Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why does a constructor call another construtor automatically ?

 
WeiJie Lim
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I executed Trial1.java, the out.println message "Success! Trial2(String s1) " prints out, which means that the empty Trial2 constructor automatically calls the 2nd Trial2 constructor.

Why does it do it ? I don't understand.

Any guidance is appreciated.

Code for Trial1.java.


Code for Trial2.java


 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15484
43
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It isn't calling the other constructor automatically. Look at line 4 of Trial2.java. From the no-args constructor of Trial2, you're calling the other constructor there explicitly, with: this("b");
 
WeiJie Lim
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper de Jong wrote:It isn't calling the other constructor automatically. Look at line 4 of Trial2.java. From the no-args constructor of Trial2, you're calling the other constructor there explicitly, with: this("b");


Thanks, I didn't know this is due to the this keyword. Found out that the this keyword can call another constructor in the same class.
 
manish ghildiyal
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
WeiJie Lim wrote:Thanks, I didn't know this is due to the this keyword. Found out that the this keyword can call another constructor in the same class.


...yes. this keyword makes you call the other constructor.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic