0
0
Swiftprogramming~10 mins

Base class and subclass in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Base class and subclass
Define Base Class
Define Subclass inheriting Base
Create Subclass Object
Access Base and Subclass Properties/Methods
Use Overridden Methods if any
Program Ends
This flow shows how a subclass inherits from a base class, creates an object, and accesses properties and methods.
Execution Sample
Swift
class Animal {
    func sound() -> String {
        return "Some sound"
    }
}

class Dog: Animal {
    override func sound() -> String {
        return "Bark"
    }
}

let pet = Dog()
print(pet.sound())
Defines a base class Animal and subclass Dog that overrides a method; then creates a Dog and prints its sound.
Execution Table
StepActionEvaluationResult
1Define class Animal with method sound()No outputAnimal class ready
2Define subclass Dog inheriting Animal, override sound()No outputDog class ready
3Create instance pet of Dogpet is Dog objectpet created
4Call pet.sound()Calls Dog's overridden sound()"Bark" returned
5Print pet.sound()Output to consoleBark
6Program endsNo further actionExecution complete
💡 Program ends after printing the overridden method result from subclass instance
Variable Tracker
VariableStartAfter Step 3After Step 4Final
petnilDog instanceDog instanceDog instance
Key Moments - 2 Insights
Why does pet.sound() print "Bark" and not "Some sound"?
Because pet is an instance of Dog, which overrides the sound() method from Animal. See execution_table step 4 where Dog's method is called.
What happens if Dog does not override sound()?
Then calling pet.sound() would use Animal's sound() method and print "Some sound". This is shown by the inheritance in execution_table steps 2 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 5?
A"Some sound"
B"Bark"
CNo output
DError
💡 Hint
Check the 'Result' column at step 5 in the execution_table.
At which step is the Dog instance created?
AStep 1
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Action' column for instance creation in execution_table.
If Dog did not override sound(), what would pet.sound() return?
A"Some sound"
B"Bark"
Cnil
DError
💡 Hint
Refer to key_moments explanation about method overriding.
Concept Snapshot
Base class defines common behavior.
Subclass inherits and can override methods.
Create subclass object to use overridden methods.
Calling method on subclass uses subclass version if overridden.
If not overridden, base class method runs.
Full Transcript
This example shows how a base class Animal defines a method sound(). The subclass Dog inherits from Animal and overrides the sound() method to return "Bark". When we create an instance pet of Dog and call pet.sound(), the overridden method in Dog runs, printing "Bark". This demonstrates inheritance and method overriding in Swift.