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 trialDhruv Mittal
932 PointsCode Challenge: How to initialise new properties in subclasses
In the editor, I have provided a class named Vehicle.
Your task is to create a subclass of Vehicle, named Car, that adds an additional stored property numberOfSeats of type Int with a default value of 4.
Once you've implemented the Car class, create an instance and assign it to a constant named someCar.
class Vehicle {
var numberOfDoors: Int
var numberOfWheels: Int
init(withDoors doors: Int, andWheels wheels: Int) {
self.numberOfDoors = doors
self.numberOfWheels = wheels
}
}
class Car: Vehicle {
let isDifferent: Bool = true
let numberOfSeats: Int = 4
override init(withDoors: Int, andWheels: Int){
super.init(withDoors: 4, andWheels: 5)
}
}
let someCar = Car(withDoors: 4, andWheels: 4)
// Enter your code below
2 Answers
Moritz Lang
25,909 PointsHi,
in Car
's initializer you hardcoded the values of withDoors
& andWheels
. You have to use the values passed through the init method instead. If the task is to add more parameters to the initializer, you just have to separat them by a comma and initialize them inside the method.
Moritz Lang
25,909 PointsYou can write it like this:
init(withDoors: Int, andWheels: Int, numberOfSeats: Int){
super.init(withDoors: 4, andWheels: 5)
self.numberOfSeats = numberOfSeats
}
However then you'd have to declare numberOfSeats
as a variable instead.
In my oppinion the est solution would be to declare numberOfSeats
as a constant and set a default value in the init method.
Dhruv Mittal
932 PointsThank you for the help!
Dhruv Mittal
932 PointsDhruv Mittal
932 PointsThank you for the reply, however, I am not sure where or how to initialise the numberOfSeats constant
Could you expand on that?