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 trialZenek Barburka
7,009 PointsHow do I create a subclass with additional property that is not set to default?
for example:
class Class { var classPropety: Int init(inputClass1: Int){ self.classPropety = inputClass1 } }
class Subclass: Class { var SubclassProperty: Int
How should the init method look like here to be able to create different instances of subclass, each of them with different SubclassProperty?
Thx
2 Answers
Steven Deutsch
21,046 PointsHey Łukasz Kozaczkiewicz,
The purpose of the init method is to make sure all the object's properties have values (nil is acceptable and the default value for all optional types).
When subclassing, you must:
- Initialize all the properties of the subclass
- initialize the properties inherited from the superclass using super.init
It's important that you do these things in this order. You can't call the initializer of the superclass until all the properties of the subclass are initialized.
class Vehicle {
var numberOfWheels: Int
init(numberOfWheels: Int) {
self.numberOfWheels = numberOfWheels
}
}
class Car: Vehicle {
var numberOfDoors: Int
init(numberOfDoors: Int, numberOfWheels: Int) {
self.numberOfDoors = numberOfDoors
super.init(numberOfWheels: numberOfWheels)
}
}
Good Luck
Zenek Barburka
7,009 PointsHey Steven, Thank you for your answer. It is all clear now. The reason I was confused was the treehouse tutorial - overriding properties, in which the override init method was shown. This is something I still don't understand :-Z The approach you shown is way easier. Thx again