Method Overriding
Overriding is when a subclass replaces one of its parent's abilities with its own custom version.
In this page:
Syntax
class Subclass: Superclass {
override func methodName() -> ReturnType {
return value // replaces the parent version
// or: super.methodName() // call the parent version
}
}
Overriding a Method
Using override func in a subclass replaces the inherited method's implementation with a new one.
Example: Overriding a Method
// Define a class `Animal`
class Animal {
// Define the function `makeSound` with no parameters and returning a String
func makeSound() -> String {
// Return `"Some generic sound"` from this function
return "Some generic sound"
}
}
// Define a class `Cat`
class Cat: Animal {
override func makeSound() -> String {
// Return `"Meow"` from this function
return "Meow"
}
}
// Declare a constant `cat`, set to `Cat()`
let cat = Cat()
// Print `cat.makeSound()` to the console
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
// Define a class `Animal`
class Animal {
// Define the function `describe` with no parameters and returning a String
func describe() -> String {
// Return `"An animal"` from this function
return "An animal"
}
}
// Define a class `Cat`
class Cat: Animal {
override func describe() -> String {
// Return `super.describe() + " that says Meow"` from this function
return super.describe() + " that says Meow"
}
}
// Declare a constant `cat`, set to `Cat()`
let cat = Cat()
// Print `cat.describe()` to the console
print(cat.describe())
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: