Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calling constructor from another constructor

 
nitinram agarwal
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I would like to know, why we cannot call the same class contructor from another constructor of the same class along with calling a super class constructor. what may be the rationale behind it.

For ex.

 
Henry Wong
author
Marshal
Pie
Posts: 21117
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nitinram agarwal wrote:Hi,
I would like to know, why we cannot call the same class contructor from another constructor of the same class along with calling a super class constructor. what may be the rationale behind it.
[/code]


The reason is because the compiler won't allow you to call the constructor of the super class twice. Hence, it will either allow you to call the super() constructor (as the first line), or the this() constructor (as the first line). If you use the this() constructor, the super() constructor will actually not be called (no implicit call), because it will be assumed that the other constructor will do it.

In your case, you can't call both the super() and this() because this will attempt to construct the super class twice. The other constructor doesn't have a call to either super() or this(), and hence, has an implicit call to the super() no-arg constructor.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic