0
0
Swiftprogramming~30 mins

Base class and subclass in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Base class and subclass
📖 Scenario: You are creating a simple program to represent animals. Each animal has a name and can make a sound. You want to create a base class for general animals and a subclass for a specific animal type.
🎯 Goal: Build a base class called Animal with a property and a method, then create a subclass called Dog that changes the sound it makes.
📋 What You'll Learn
Create a base class Animal with a name property and a makeSound() method
Create a subclass Dog that inherits from Animal
Override the makeSound() method in Dog to print a dog-specific sound
Create an instance of Dog and print its sound
💡 Why This Matters
🌍 Real World
Understanding base classes and subclasses helps organize code when many objects share common features but behave differently.
💼 Career
Inheritance is a key concept in object-oriented programming used in app development, game programming, and software design.
Progress0 / 4 steps
1
Create the base class Animal
Create a base class called Animal with a name property of type String and an initializer that sets name. Add a method called makeSound() that prints "Some generic animal sound".
Swift
Need a hint?

Remember to create an initializer init(name: String) to set the name property.

2
Create the subclass Dog
Create a subclass called Dog that inherits from Animal. Override the makeSound() method to print "Woof!".
Swift
Need a hint?

Use override keyword to change the behavior of makeSound() in the subclass.

3
Create an instance of Dog
Create a variable called myDog and assign it an instance of Dog with the name "Buddy".
Swift
Need a hint?

Use let myDog = Dog(name: "Buddy") to create the instance.

4
Call makeSound() on myDog
Call the makeSound() method on the myDog instance to print the dog's sound.
Swift
Need a hint?

Use myDog.makeSound() to call the method.