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!

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


Zenek Barburka
Zenek Barburka
7,009 Points

How 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?


2 Answers

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Ł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:

  1. Initialize all the properties of the subclass
  2. 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
Zenek Barburka
7,009 Points

Hey 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