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 trialAbner Medina
4,076 PointsSo when setting defaults to the let variables of the original class, we need to use the keyword 'override? please expand
I kind of get why but in the examples in the course, only functions were overridden, I just wanna know a bit more as to why we need an override in this case
class Vehicle {
let wheels: Int
let doors: Int
// Designated initializer
init(wheels:Int, doors:Int){
self.wheels = wheels
self.doors = doors
}
}
class Car: Vehicle {
// A car must default to 4 wheels and 4 doors
override init(wheels:Int, doors:Int){
// call super.init
super.init(wheels:wheels, doors:doors)
}
convenience init () {
self.init(wheels:4, doors:4)
}
}
1 Answer
kjvswift93
13,515 PointsWhen one class is derived from another, the new class is called the subclass and the class it derives from is called the superclass. The subclass usually adds its own properties and methods to those inherited from the superclass, however a subclass also has the ability to "override" methods and properties of the superclass by actually redefining them itself. In the case of the challenge, the Vehicle class has two 'stored properties' named 'wheels' and 'doors', which ARE given initial values by means of the initializer method. The override keyword is used within a subclass to tell the compiler that the redefinition is intentional, and that you haven't accidentally created a method or property with the same name.