Calling super for parent behavior
📖 Scenario: Imagine you are creating a simple app with different types of vehicles. Each vehicle can start its engine, but some vehicles have extra steps when starting. You will learn how to use super to call the parent class behavior and add extra steps in child classes.
🎯 Goal: You will build a small Swift program with a parent class Vehicle and a child class Car. You will override a method in the child class and call the parent method using super to keep the original behavior and add new behavior.
📋 What You'll Learn
Create a class called
Vehicle with a method startEngine() that prints "Engine started".Create a subclass called
Car that inherits from Vehicle.Override the
startEngine() method in Car and call the parent method using super.startEngine().Add an extra print statement in
Car's startEngine() method that prints "Car is ready to go!".Create an instance of
Car and call its startEngine() method to see both messages.💡 Why This Matters
🌍 Real World
In real apps, many classes inherit from others and override methods to add or change behavior. Using <code>super</code> helps keep the original behavior while extending it.
💼 Career
Understanding inheritance and calling parent methods is essential for Swift developers working on iOS apps, especially when working with UIKit or SwiftUI where subclassing is common.
Progress0 / 4 steps