Bird
Raised Fist0
Swiftprogramming~10 mins

Preventing overrides with final in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Preventing overrides with final
Define class
↓
Mark method/property as final
↓
Try to override in subclass
↓
Compiler error: Override not allowed
↓
Use final to protect code
This flow shows how marking a method or property as final stops subclasses from changing it, causing a compile error if override is attempted.
Execution Sample
Swift
class Animal {
    final func sound() {
        print("Animal sound")
    }
}

class Dog: Animal {
    // override func sound() { print("Bark") } // Error
}
Defines a class with a final method, then a subclass tries to override it but causes a compile error.
Execution Table
StepActionCode LineResultNotes
1Define class Animalclass Animal { ... }Class Animal createdNo issues
2Define final method sound()final func sound() { ... }Method sound() marked finalPrevents overrides
3Define subclass Dogclass Dog: Animal { ... }Class Dog createdInherits Animal
4Attempt to override sound()// override func sound() { print("Bark") }Compile errorCannot override final method
5Remove override or keep finalN/ACode compilesOverride prevented by final
💡 Execution stops because overriding a final method causes a compile-time error.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
Animal.soundNot definedDefined as finalInherited by DogOverride attempt failsFinal method remains unchanged
Key Moments - 2 Insights
Why does the compiler give an error when trying to override a final method?
Because the method is marked final (see execution_table step 4), Swift prevents any subclass from changing it to keep behavior consistent.
Can a final method be called normally from a subclass?
Yes, subclasses inherit and can call the final method but cannot override it (see execution_table step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 4 when Dog tries to override sound()?
AThe method is ignored
BThe override works and prints "Bark"
CCompile error occurs
DThe program crashes at runtime
💡 Hint
Check execution_table row 4 for the result of the override attempt.
According to variable_tracker, what is the status of Animal.sound after step 2?
ANot defined
BDefined as final
COverridden by Dog
DRemoved
💡 Hint
Look at variable_tracker row for Animal.sound after step 2.
If the final keyword is removed from sound(), what would change in the execution table?
AStep 4 would compile without error
BStep 3 would fail
CStep 2 would cause error
DNo change at all
💡 Hint
Refer to execution_table step 4 where the error occurs due to final keyword.
Concept Snapshot
final keyword in Swift
- Use final before methods or properties
- Prevents subclasses from overriding
- Compiler error if override attempted
- Keeps code behavior safe and consistent
- Subclasses can still call final methods
Full Transcript
This example shows how to prevent subclasses from changing a method by marking it final. The Animal class has a final method sound(). When Dog tries to override sound(), the compiler stops it with an error. This protects the method from being changed. Subclasses can still use the method but cannot override it. Removing final allows overriding. This helps keep code safe and predictable.

Practice

(1/5)
1.

What does the final keyword do in Swift?

easy
A. Makes a method asynchronous
B. Allows a class to be subclassed multiple times
C. Marks a variable as constant
D. Prevents a class or method from being overridden or subclassed

Solution

  1. Step 1: Understand the purpose of final

    The final keyword in Swift is used to stop classes or methods from being changed by subclasses.
  2. Step 2: Identify what final prevents

    It prevents overriding methods or subclassing classes, ensuring the code stays as originally designed.
  3. Final Answer:

    Prevents a class or method from being overridden or subclassed -> Option D
  4. Quick Check:

    final stops overrides = A [OK]
Hint: Remember: final means no changes allowed to class or method [OK]
Common Mistakes:
  • Confusing final with constant variables
  • Thinking final allows subclassing
  • Mixing final with async keyword
2.

Which of the following is the correct way to declare a method that cannot be overridden in Swift?

class Vehicle {
    _____ func startEngine() {
        print("Engine started")
    }
}
easy
A. override
B. mutating
C. final
D. static

Solution

  1. Step 1: Identify the keyword to prevent overriding

    In Swift, the final keyword is used before a method to stop it from being overridden in subclasses.
  2. Step 2: Check the method declaration

    Placing final before func correctly marks the method as non-overridable.
  3. Final Answer:

    final -> Option C
  4. Quick Check:

    Use final before func to prevent override [OK]
Hint: final before func means no override allowed [OK]
Common Mistakes:
  • Using override keyword incorrectly
  • Confusing static with final
  • Using mutating which is for structs
3.

What will happen when you run this Swift code?

class Animal {
    final func sound() {
        print("Animal sound")
    }
}

class Dog: Animal {
    override func sound() {
        print("Bark")
    }
}

let pet = Dog()
pet.sound()
medium
A. Prints "Animal sound"
B. Compile-time error due to overriding a final method
C. Prints "Bark"
D. Runtime error

Solution

  1. Step 1: Identify the use of final in the base class

    The method sound() in Animal is marked as final, so it cannot be overridden.
  2. Step 2: Check the subclass method override

    The Dog class tries to override sound(), which causes a compile-time error because overriding a final method is not allowed.
  3. Final Answer:

    Compile-time error due to overriding a final method -> Option B
  4. Quick Check:

    Overriding final method = Compile error [OK]
Hint: Overriding final method causes compile error [OK]
Common Mistakes:
  • Assuming it prints "Bark"
  • Thinking it prints base method output
  • Expecting runtime error instead of compile error
4.

Find the error in this Swift code and fix it:

final class Vehicle {
    func drive() {
        print("Driving")
    }
}

class Car: Vehicle {
    override func drive() {
        print("Car driving")
    }
}
medium
A. Remove final from Vehicle class
B. Remove override from Car's drive method
C. Change Vehicle to a struct
D. Add final to Car class

Solution

  1. Step 1: Identify the use of final on the Vehicle class

    The Vehicle class is marked as final, so it cannot be subclassed.
  2. Step 2: Check subclass declaration

    The Car class tries to subclass Vehicle, which causes a compile-time error because subclassing a final class is not allowed.
  3. Final Answer:

    Remove final from Vehicle class -> Option A
  4. Quick Check:

    Subclassing final class = Error; remove final [OK]
Hint: final class cannot be subclassed; remove final to fix [OK]
Common Mistakes:
  • Trying to override without removing final
  • Adding final to subclass instead of base
  • Changing class to struct unnecessarily
5.

You want to create a base class BankAccount with a method calculateInterest() that should never be changed by subclasses. However, subclasses can add new methods. How should you declare BankAccount and calculateInterest()?

hard
A. Declare BankAccount normally and calculateInterest() as final
B. Declare both BankAccount and calculateInterest() as final
C. Declare BankAccount as final and calculateInterest() normally
D. Declare BankAccount as a struct and calculateInterest() as final

Solution

  1. Step 1: Understand the requirement for subclassing

    The base class BankAccount should allow subclasses, so it must NOT be final.
  2. Step 2: Protect the method from being overridden

    Mark calculateInterest() as final to prevent subclasses from changing it.
  3. Final Answer:

    Declare BankAccount normally and calculateInterest() as final -> Option A
  4. Quick Check:

    final method, normal class = C [OK]
Hint: final method stops override; class normal allows subclass [OK]
Common Mistakes:
  • Making the whole class final, blocking subclassing
  • Not marking method as final, allowing override
  • Using struct instead of class incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard