0
0
Swiftprogramming~15 mins

Preventing overrides with final in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Preventing Overrides with final in Swift
📖 Scenario: Imagine you are creating a simple app to manage vehicles. You want to make sure that certain behaviors of your vehicle classes cannot be changed by mistake in subclasses.
🎯 Goal: You will create a base class with a method that cannot be overridden by subclasses using the final keyword. This helps keep your code safe and predictable.
📋 What You'll Learn
Create a class called Vehicle with a method startEngine() that prints a message.
Add the final keyword to the startEngine() method to prevent overriding.
Create a subclass called Car that inherits from Vehicle.
Try to override the startEngine() method in Car (this should cause an error if uncommented).
Create an instance of Car and call the startEngine() method.
Print the output to see the behavior.
💡 Why This Matters
🌍 Real World
In real apps, you often want to protect core behaviors of your classes so they don't change unexpectedly when others extend your code.
💼 Career
Understanding <code>final</code> helps you write safer, more reliable Swift code, a skill valued in iOS and macOS development jobs.
Progress0 / 4 steps
1
Create the Vehicle class with a startEngine() method
Create a class called Vehicle with a method startEngine() that prints "Engine started".
Swift
Need a hint?

Use class Vehicle {} and define func startEngine() inside it.

2
Make startEngine() method final to prevent overrides
Add the final keyword before the func startEngine() method in the Vehicle class to prevent it from being overridden.
Swift
Need a hint?

Write final func startEngine() to stop subclasses from changing this method.

3
Create a Car subclass inheriting from Vehicle
Create a subclass called Car that inherits from Vehicle. Inside Car, add a commented-out attempt to override startEngine() method that prints "Car engine started".
Swift
Need a hint?

Use class Car: Vehicle {} and inside it write a commented override of startEngine().

4
Create a Car instance and call startEngine()
Create an instance called myCar of the Car class and call the startEngine() method on it. Print the output.
Swift
Need a hint?

Write let myCar = Car() and then myCar.startEngine().