Swift: Inheritance

Inheritance in Swift:

We defined a class, created instances, and added an init() method in the previous exercises. However, the structures of all of these concepts were the same. “How are classes different from structures?” we must now ask. Let’s discuss about inheritance in Swift.

When we define a class, it can inherit (or take on) the properties and methods of another class. This is a capability that structures do not provide. In addition, inheritance is a key feature that distinguishes classes from other types in Swift.

When one class inherits from another, the following happens:

  • A subclass is a class that inherits from another class.
  • Its superclass is the class from which it derives.

To make a class that inherits from another, we place the name of the class we’re inheriting from (superclass) after the name of the class we’re making (subclass), as shown below:

class Subclass: Superclass {
     // class definition
} ;

So, let’s say we have a class called Employe that looks like this:

class Employe {
  var salary = 0.0 ;
 
  func addSalary(amount: Double) {
    salary += amount ;
  }
 
  func deduction(amount: Double) {
    salary -= amount ;
  }
} ;

It has:

  • The .salary property that stores the salary amount
  • The method .addSalary() that adds to the salary
  • The .deduction() method for deducting miscellaneous charges from the salary

In addition, we’d like to create a new Manager class that inherits from Employe:

class Manager: Employe {
  var bonus = 0.0 ;
 
  func addBonus() {
    bonus = salary * 1.5 ;
    self.addSalary(amount: bonus) ;
  }
} ;

The new Manager class (subclass) inherits all of the properties and methods of the Employe class (superclass), including the .salary property and the .addSalary() and .deduction() methods.

The Manager class also defines the following:

  • The .bonus property that stores the bonus that is calculated.
  • The .addBonus() method that calculates the bonus.

These will only be available in Manager instances.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: