This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling constructor from another constructor  RSS feed

 
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
Sheriff
Posts: 23283
125
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
Boost this thread!