To continue the conversation on inheritance, a subclass can provide its own custom implementation of a property or method that is inherited from a superclass. This is known as overriding.
To override a method, we can redeclare it in the subclass and add the override
keyword to let the compiler know that we aren’t accidentally creating a method with the same name as the one in the parent class.
override func name(parameter) {
}
So here’s the BankAccount
class again:
class BankAccount { var balance = 0.0 func deposit(amount: Double) { balance += amount } func withdraw(amount: Double) { balance -= amount } }
Suppose we want a new SavingsAccount
class and we want to override the .withdraw()
method from its superclass BankAccount
:
class SavingsAccount: BankAccount { var interest = 0.0 var numWithdraw = 0 func addInterest() { let interest = balance * 0.01 self.deposit(amount: interest) } override func withdraw(amount: Double) { balance -= amount numWithdraw += 1 } }
Here, the new .withdraw()
method not only subtracts amount
from balance
, but it also increments numWithdraw
.
Instructions
Let’s take a look at the Order
superclass and the DeliveryOrder
subclass again. Something is missing in the new receipt… the newly added delivery fee!
Inside the new DeliveryOrder
class, override the .printReceipt()
method to include the delivery fee so that the receipt looks like:
Items: ["Ramen", "Diet Coke"] Subtotal: $14.69 Tip: $2.0 Delivery: $3.0 Total: $19.69