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

constructor of subclass call to super  RSS feed

 
Chris Yates
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose i have two classes Vehicle and subclass Car.
In car i have this copy constructor which takes Car as parameter.



Can i call super with c or does it need cast to Vehicle? I would like to know details of this behinds the scenes.
Thanks.
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First class 'Car' should extends class 'Vehicle'. Also you need to have constructor which takes 'Vehicle' type variable in super class.

After extending the class you can have constructor of any type ('Car' or 'Vehicle').
 
Chris Yates
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




I can call super here with c right? No need for cast of Car c to Vehicle, iam i right?
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. This code doesn't compiles. We don't extend this way. Here is the example:





Output:

 
Campbell Ritchie
Marshal
Posts: 55717
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tushar Goel wrote:. . .. . .
That bit is misleading since you don't have a default constructor.

Surely manufacturer and number of passengers are attributes of the Vehicle class not specifically the Car class. You may wish to make passengers default to 0. Or, if I read the post correctly, it reads doors. Again you may wish set a default number of doors. 0 is permissible. I can see no point in passing a superclass object to a subclass' copy constructor, except under the following rubric:-
I just wanted to see what happens if …
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell.. I suppose sub class passing its own reference also doesn't make sense...
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chris Yates wrote:I can call super here with c right? No need for cast of Car c to Vehicle, iam i right?

Other than what Tashar and Campbell pointed out: No.

Car is a subclass of Vehicle, therefore every Car is a Vehicle - hence: no cast needed.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!