Introducing super

You may have also noticed the line super.recordGrade(grade) in the overridden method. The super keyword is similar to self, except it will invoke the method in the nearest implementing superclass. In the example of recordGrade(_:) in StudentAthlete, calling super.recordGrade(grade) will execute the method as

defined in the Student class.

Remember how inheritance let you define Person with first name and last name properties and avoid repeating those properties in subclasses? Similarly, being able to call the superclass methods means you can write the code to record the grade once in Student and then call “up” to it as needed in subclasses.

Although the compiler doesn’t enforce it, it’s important to call super when overriding a method in Swift. The super call is what will record the grade itself in the grades array, because that behavior isn’t duplicated in StudentAthlete. Calling super is also a way of avoiding the need for duplicate code in StudentAthlete and Student.

results matching ""

    No results matching ""