Learn
Classes
Inheritance

In the previous exercises, we’ve defined a class, created instances, and added an init() method. But all these concepts were the same in structures. So now we have to ask, “how are classes different from structures?”.

When we define a class, it can inherit, or take on, another class’s properties and methods. This is an additional capability that structures don’t offer. Moreover, inheritance is a fundamental behavior that differentiates classes from other types in Swift.

When one class inherits from another:

  • The new inheriting class is known as a subclass.
  • The class it inherits from is known as its superclass.

To create a class that inherits from another, we put the name of the class we’re inheriting from (superclass) after the name of the class we’re creating (subclass), like so:

class Subclass: Superclass {

}

So suppose we have a BankAccount class that looks like:

class BankAccount { var balance = 0.0 func deposit(amount: Double) { balance += amount } func withdraw(amount: Double) { balance -= amount } }

It has:

  • a .balance property that stores the amount of money
  • a .deposit() method that adds to the balance
  • a .withdraw() method that takes from the balance

And we want a new SavingsAccount class that inherits from BankAccount:

class SavingsAccount: BankAccount { var interest = 0.0 func addInterest() { let interest = balance * 0.005 self.deposit(amount: interest) } }

Here, the new SavingsAccount class (subclass) automatically gains all of the characteristics of BankAccount class (superclass), such as its .balance property and its .deposit() and .withdraw() methods.

In addition, the SavingsAccount class defines the following:

  • a .interest property that stores the interest rate
  • a .addInterest() method that deposits the interest

And only SavingsAccount instances will have these.

Instructions

1.

Given an Orders class that stores information about a food order with the following properties and method:

  • .items: an array of food items
  • .subtotal: the total price of the items
  • .tip: the tip amount
  • .total: the subtotal plus the tip
  • .printReceipt(): prints out a receipt

Let’s define a new DeliveryOrder class that inherits from it. And include a new property called .deliveryFee that has a default value of 2.0.

Folder Icon

Take this course for free

Already have an account?