• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why does a constructor call another construtor automatically ?

 
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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


 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic