This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Why does a constructor call another construtor automatically ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why does a constructor call another construtor automatically ?" Watch "Why does a constructor call another construtor automatically ?" New topic
Author

Why does a constructor call another construtor automatically ?

WeiJie Lim
Ranch Hand

Joined: Sep 05, 2012
Posts: 85
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

Joined: Aug 16, 2005
Posts: 14074
    
  16

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");


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
WeiJie Lim
Ranch Hand

Joined: Sep 05, 2012
Posts: 85
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

Joined: Jan 12, 2013
Posts: 136
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why does a constructor call another construtor automatically ?
 
Similar Threads
super(x,y) and this() in one constructor
Why i am getting this error?
Doubt in equals method
StringBuffer question
replacing characters