Start learning free

LESSON 38 OF 71 · OBJECT-ORIENTED PROGRAMMING

Base Keyword in Swift: Calling the Parent with super

Practice Read the full explanation

TL ; DR:

Inside an override func, super.bark() calls the parent class's version of bark on the same object. This lets you extend the parent's behavior instead of replacing it.


class Puppy: Dog {
    override init(_ name: String) { super.init(name) }
    override func bark() {
        super.bark()   // do everything the parent did
        print("Yip! Said \(name)")
    }
}

Why it matters

Overriding a method replaces the parent's behavior. Often you want to extend it instead: keep what the parent did and add something more. A typical example is a save method: the parent writes the row to the database, and a subclass runs the parent's save first and then writes a log line.

Your task

The Puppy class already overrides bark(), but the body is empty. Inside Puppy.bark():

  1. call the parent's version with super.bark(), so Woof! I am <name> still prints;
  2. then print("Yip! Said \(name)").

Notes:

  • Swift requires the word override whenever you redefine a parent's method or initializer. super.init(name) (already written) initializes the Dog part.
  • \(name) inside a string inserts the value of name.

The driver (already written, it runs when you press Run):

let buddy = Puppy("Buddy")
buddy.bark()
let rex = Puppy("Rex")
rex.bark()
let dog = Dog("Max")
dog.bark()
  • buddy is a Puppy: its bark prints the parent's line, then its own.
  • rex is another Puppy: the names come from the object, nothing is hard-coded.
  • dog is a plain Dog: its bark is unchanged and prints only the parent's line, with no Yip!.

Expected output:

Woof! I am Buddy
Yip! Said Buddy
Woof! I am Rex
Yip! Said Rex
Woof! I am Max
STEP 1 OF 2
    Ctrl + Enter to check

    SWIFT · OBJECT-ORIENTED PROGRAMMING

    Base Keyword in Swift, explained

    Problem overview

    The starter code has a Dog class whose bark() prints Woof! I am <name>, and a Puppy subclass that overrides bark() with an empty body. The lesson asks you to fill in that body so a puppy first does everything a dog does and then adds a line of its own, Yip! Said <name>.

    The driver creates two puppies, Buddy and Rex, and one plain dog, Max. Buddy and Rex each print two lines. Max prints only the dog's line, because Dog itself is unchanged. The expected output has five lines in total:

    Woof! I am Buddy
    Yip! Said Buddy
    Woof! I am Rex
    Yip! Said Rex
    Woof! I am Max
    

    Approach: extend the parent instead of replacing it

    When a subclass overrides a method, its version takes over completely. Whatever the parent's method did no longer happens unless the new body does it again. You could copy the parent's print line into Puppy.bark(), but then every change to Dog.bark() would need the same change in the subclass.

    A better way is to ask the parent to do its part. Inside a method, super refers to the parent class, and super.bark() runs Dog's version of bark on the same object. The name still comes from the puppy itself, so nothing is hard-coded.

    The same pattern shows up whenever a subclass should add to a parent's behaviour: the parent does its general job, and the subclass finishes with the part that is specific to it.

    Step by step

    1. Call super.bark() first. This prints Woof! I am Buddy. Without it, the puppy would print only its own line and the parent's behaviour would be lost.
    2. Print the puppy's own line. Use string interpolation, "Yip! Said \(name)". The name property is inherited from Dog, so the puppy can read it directly.

    Because the parent's method is called rather than copied, the puppy keeps up with the parent. If Dog.bark() later prints something different, every puppy picks up the change without being edited.

    The order matters: the parent's line comes first and the extra line second, which is how the expected output reads.

    The solution in Swift

    class Dog {
        var name: String
        init(_ name: String) { self.name = name }
        func bark() {
            print("Woof! I am \(name)")
        }
    }
    
    class Puppy: Dog {
        override init(_ name: String) { super.init(name) }
        override func bark() {
            super.bark()
            print("Yip! Said \(name)")
        }
    }
    
    class Solution {
        func mainFunction() {
            let buddy = Puppy("Buddy")
            buddy.bark()
            let rex = Puppy("Rex")
            rex.bark()
            let dog = Dog("Max")
            dog.bark()
        }
    }
    

    Details worth knowing

    • override is mandatory. Redefining a parent's method without it is a compile error: overriding declaration requires an 'override' keyword. The same applies to the initializer, which is why Puppy declares override init(_ name: String).
    • super.init(name) initializes the Dog part of the object, which is what stores the name. The starter already has it. Since Puppy adds no stored properties of its own, Swift would also let it inherit Dog's initializer without this override, but writing it out shows the same super idea applied to initializers.
    • One object, two layers. A Puppy is a single object that contains everything a Dog has. That is why super.bark() sees the same name as the puppy's own code: there is no separate dog hiding inside.
    • Dynamic dispatch. The method that runs depends on the object's real class, not on the type of the variable. With let d: Dog = Puppy("Ann"), calling d.bark() prints Woof! I am Ann and then Yip! Said Ann.
    • super can go anywhere in the body. If a subclass printed its line first and called super.bark() second, the order of the output would flip. Here the parent goes first.

    Trying the other order

    To see that the position of the call matters, consider a different subclass that prints before calling the parent:

    class LoudPuppy: Dog {
        override func bark() {
            print("Yip first")
            super.bark()
        }
    }
    LoudPuppy("Zed").bark()
    

    It prints the lines in the opposite order:

    Yip first
    Woof! I am Zed
    

    Nothing else changes. super.bark() is an ordinary statement, so you choose where it sits relative to the subclass's own code. A subclass can also call the parent's method conditionally, or more than once, though this lesson only needs the simple case.

    Edge cases and common mistakes

    • Writing bark() instead of super.bark(). Inside Puppy.bark(), a plain bark() calls the puppy's own method again, so the method keeps calling itself and never finishes. super. is what reaches the parent's version.
    • Forgetting the call entirely. The code compiles, but the puppy prints only Yip! Said Buddy and the Woof! line disappears.
    • Hard-coding a name. The names must come from the object. Rex has to print Rex, and a hard-coded Buddy would fail on the second puppy.
    • Changing Dog. The plain dog must keep printing a single line, so all the new behaviour belongs in Puppy.

    Testing

    Beyond the lesson's driver, it is worth checking a puppy stored in a Dog variable, since that is how code often holds objects of mixed classes:

    let d: Dog = Puppy("Ann")
    d.bark()
    Dog("Max").bark()
    
    Woof! I am Ann
    Yip! Said Ann
    Woof! I am Max
    

    The first call still runs the puppy's version, and the plain dog still prints one line. If both behaved the same, the override would not be reaching the object.

    Key takeaways

    • An override replaces the parent's method; super.method() brings the parent's behaviour back inside it.
    • Swift requires override on every redefined method or initializer.
    • The position of the super call decides whether the extra work happens before or after the parent's.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free