Introduction
A class can inherit methods, properties, and characteristics of another class. When one class inherits from another, the inheriting class is a subclass, and the class it inherits from is a superclass. Classes in Swift call and access methods, properties, and subscripts belonging to superclass. They then provide their own overriding versions of methods, properties, and subscripts to refine or modify behavior.
Base Class
Any class that does not inherit from another class is known as a base class. Swift classes do not inherit from a universal base class. The class which is defined without specifying the superclass automatically becomes a base class. The below base class has two properties as numberOfWheels and maxPassengers. These properties are used by methods as a description which returns a String description.
- class Vehicle
- {
- var numberOfWheels : Int
- var maxPassengers : Int
- func description () - > String
- return "\(numberOfWheels) wheels; up to \(maxPassengers) passengers"
- }
- init ()
- {
- numberOfWheels = 0
- maPassengers = 1
- }
The vehicle class defines an initializer to set up its properties. Initializers are used to create a new instance of a type. Initializers are not methods and it prepares a new instance for use, and ensure all properties of instance have valid initial values.
Subclassing
Subclassing is the act of basing a new class on an existing class. The subclass inherits characteristics from the existing class. The new characteristics can be added to the subclass. Write the superclass name after the original class name to indicate that a class has a superclass. In the below example, Bicycle is a subclass of vehicle and vehicle is the superclass of the bicycle. The new Bicycle class automatically gains all characteristics of the vehicle as its masPassengers and numberOfWheel properties.
- class Bicycle : Vehicle
- {
- init()
- {
- super : init()
- numberOfWheels = 2
- }
- }
Subclasses are only allowed to modify variable properties of the superclass during initialization. The inherited constant properties of subclasses cannot be modified. The below example creates a subclass of Bicycle for two-seater bicycle is a tandem and it inherits the two properties from Bicycle and It inherits these properties from the vehicle.

Join the conversation! Your thoughts help the community grow.