The super Keyword
super is how a subclass reaches back up to its parent class to use the parent's own version of something.
Calling super.init in a Subclass Initializer
When a subclass adds its own properties, its initializer typically sets those first, then calls super.init(...) to let the superclass initialize its own properties.
Example: Calling super.init in a Subclass Initializer
class Vehicle {
var wheels: Int
init(wheels: Int) {
self.wheels = wheels
}
}
class Car: Vehicle {
var brand: String
init(brand: String) {
self.brand = brand
super.init(wheels: 4)
}
}
let car = Car(brand: "Ford")
print("\(car.brand) has \(car.wheels) wheels")
Login to try C/C++/Java/PHP code in the editor
Using super in an Overridden Method
super.methodName() inside an override calls the superclass's original implementation of that method.
Example: Using super in an Overridden Method
class Greeter {
func greet() -> String {
return "Hello"
}
}
class EnthusiasticGreeter: Greeter {
override func greet() -> String {
return super.greet() + "!!!"
}
}
print(EnthusiasticGreeter().greet())
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting to call
super.init(...)in a subclass's custom initializer when the superclass has its own required setup. - Using
superoutside of a class (e.g. in a struct), where it has no meaning since structs don't support inheritance. - Calling
super.method()at the wrong point in an override, when the parent behavior was meant to run before or after new logic, not instead of it.
Chapter Summary
superrefers to the current class's immediate superclass.super.init(...)calls the superclass's initializer, often required to set up inherited properties.super.method()invokes the superclass's version of an overridden method.supercan only be used within a subclass, never in a class with no superclass.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: