Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kevin Walker
2,354 PointsOverriding Init and properties
One thing I was wondering when i watched the videos was why, when doing the override for the init in SuperEnemy, do we put the code for setting the life property within the override?
class Enemy { var life: Int = 10 let position: Point
init(x: Int, y: Int)
{
self.position = Point(x: x, y: y)
}
func decreaseHealth(factor: Int){
life -= factor
}
}
class SuperEnemy: Enemy { let isSuper: Bool = true
override init(x: Int, y: Int)
{
super.init(x: x, y: y)
self.life = 50
}
}
1 Answer
Oliver Duncan
16,642 PointsLike Yigit says, we override the init method because all instances of SuperEnemy inherit, and are initialized with, a life property with a value of ten. We want the SuperEnemy to have a life of 50, so we override the initializer and give its life a value of 50.
If you're wondering why we don't override the life variable in the beginning of the subclass declaration, I'm not sure. It would be nice if we could just write "override var life = 50," but trying it out results in a compiler error. Probably something to do with what Swift does under the hood.
Yigit Yilmaz
6,245 PointsYigit Yilmaz
6,245 PointsWhile using 'life' in 'Enemy' it is a variable for using decreaseHealth. 'SuperEnemy' subclass already have 'life' variable but must assign new value. It is logic of inheritance. Super Enemies' life must 50 not 10. For this goal, we re-assigned 'life' in override init.