← Back to Swift Course | Chapter 9: Inheritance & Protocols | Lesson 2 of 7

Method Overriding

Overriding is when a subclass replaces one of its parent's abilities with its own custom version.

Overriding a Method

Using override func in a subclass replaces the inherited method's implementation with a new one.

Example: Overriding a Method

markup
class Animal {
    func makeSound() -> String {
        return "Some generic sound"
    }
}
class Cat: Animal {
    override func makeSound() -> String {
        return "Meow"
    }
}
let cat = Cat()
print(cat.makeSound())

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

markup
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())
Common Mistakes
  1. Forgetting the override keyword when redefining an inherited method; Swift requires it explicitly to prevent accidental overrides.
  2. Trying to override a property or method marked final; Swift will refuse to compile.
  3. 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 override keyword.
  • final prevents 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.