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 trialSam Belcher
3,719 Pointssuper init and class inheritance
I am really confused with super inits and when to override an init value. I understand how to make a class but basically I am stuck on inheritance
3 Answers
Jeff McDivitt
23,970 PointsHi Sam -
You state that you know how to make a class so I assume that you are ok with initialization as well. If not let me know, but anyway on the inheritance.
Let's say we have a class
class Machine {
var id: Int
var name: String
var automaticallyRuns: Bool
init(id: Int, name: String, automaticallyRuns: Bool) {
self.id = id
self.name = name
self.automaticallyRuns = automaticallyRuns
}
}
Now lets say we have another class that inherits from Machine
class SuperMachine: Machine {
var partsMade: String
init(id: Int, name: String, automaticallyRuns: Bool,partsMade: String) {
self.partsMade = partsMade
super.init(id: id, name: name, automaticallyRuns: automaticallyRuns)
}
}
We added something to the second class var partsMade: String, but the second class also inherits everything from its parent class (see below)
var myMachine = Machine(id: 1, name: "My Machine", automaticallyRuns: false)
var mySuperMachine = SuperMachine(id: 2, name: "My Super Machine", automaticallyRuns: true, partsMade: "Metal")
Sam Belcher
3,719 Pointsthanks! but I am still a little confused with the function of the super init, and I don't understand why the variables of the super init have the same type as their name. Also, when do you override an init? and when do you write additional code under the super init?
Jeff McDivitt
23,970 PointsHi Sam -
This tutorial is probably the best way I have seen it explained. If you still have questions let me know