Method Overriding
Overriding is when a subclass replaces one of its parent's abilities with its own custom version.
In this page:
Overriding a Method
Using override func in a subclass replaces the inherited method's implementation with a new one.
Example: Overriding a Method
class Animal {
func makeSound() -> String {
return "Some generic sound"
}
}
class Cat: Animal {
override func makeSound() -> String {
return "Meow"
}
}
let cat = Cat()
print(cat.makeSound())
Login to try C/C++/Java/PHP code in the editor
Calling super in an Override
Inside an override, calling super.method() runs the parent class's original implementation, letting you extend rather than fully replace it.
Example: Calling super in an Override
class Animal {
func describe() -> String {
return "An animal"
}
}
class Cat: Animal {
override func describe() -> String {
return super.describe() + " that says Meow"
}
}
let cat = Cat()
print(cat.describe())
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting the
overridekeyword when redefining an inherited method; Swift requires it explicitly to prevent accidental overrides. - Trying to override a property or method marked
final; Swift will refuse to compile. - Overriding a method but forgetting to call
super.method()when the parent's behavior still needs to run alongside the new behavior.
Chapter Summary
- Overriding an inherited method or property requires the explicit
overridekeyword. finalprevents a method, property, or class from being overridden or subclassed.super.method()calls the parent class's original implementation from within the override.- Overriding lets a subclass customize inherited behavior instead of just reusing it as-is.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: