Start learning free

LESSON 38 OF 70 · OBJECT-ORIENTED PROGRAMMING

Base Keyword in Scala: Calling the Parent with super

Practice Read the full explanation

TL ; DR:

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


class Puppy(name: String) extends Dog(name) {
    override def bark(): Unit = {
        super.bark()   // do everything the parent did
        println(s"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 println(s"Yip! Said $name").

Notes:

  • extends Dog(name) passes the name to Dog's constructor. override is required when you redefine a method of the parent.
  • s"...$name" is a string with the value of name inserted.

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

val buddy = Puppy("Buddy")
buddy.bark()
val rex = Puppy("Rex")
rex.bark()
val 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

    SCALA · OBJECT-ORIENTED PROGRAMMING

    Base Keyword in Scala, explained

    Problem overview

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

    The driver creates two puppies, Buddy and Rex, and a plain Dog called Max. The expected output is two lines for each puppy and one line for the dog:

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

    Approach: extend the parent's method, don't replace it

    When a subclass overrides a method, its version takes over completely. The parent's body doesn't run unless the new body asks for it. Other languages call it "base"; Scala uses super, which stands for the parent class, and super.bark() runs Dog's version of bark on the current object.

    The difference is easy to see with two subclasses of the same Dog. The first overrides bark and prints only its own line. The second calls super.bark() twice:

    class Dog(val name: String) {
        def bark(): Unit = println(s"Woof! I am $name")
    }
    class Quiet(name: String) extends Dog(name) {
        override def bark(): Unit = println(s"Yip! Said $name")
    }
    class Loud(name: String) extends Dog(name) {
        override def bark(): Unit = { super.bark(); super.bark() }
    }

    Calling bark() on Quiet("Buddy") prints only Yip! Said Buddy: the parent's line is gone. Calling it on Loud("Rex") prints Woof! I am Rex twice, because each super.bark() runs the parent's code.

    That is the whole idea of the lesson. A Puppy must keep the parent's behaviour and add to it, so the body needs the parent call and then one more line.

    Step by step

    1. Call super.bark() first. This produces Woof! I am Buddy, exactly the line a plain dog prints. Without this call the puppy would replace the dog's bark instead of extending it.
    2. Print the puppy's own line. Use an s string, s"Yip! Said $name", so the current object's name is inserted. Nothing is hard-coded, which is why Rex gets its own name in the output.

    The order matters here: the expected output has the parent's line before the puppy's line, so the parent call comes first.

    The solution in Scala

    class Dog(val name: String) {
        def bark(): Unit = {
            println(s"Woof! I am $name")
        }
    }
    
    class Puppy(name: String) extends Dog(name) {
        override def bark(): Unit = {
            super.bark()
            println(s"Yip! Said $name")
        }
    }
    
    class Solution {
        def mainFunction(): Unit = {
            val buddy = Puppy("Buddy")
            buddy.bark()
            val rex = Puppy("Rex")
            rex.bark()
            val dog = Dog("Max")
            dog.bark()
        }
    }

    Details worth knowing

    • override is required. Redefining a method that the parent already has without the keyword is a compile error: the compiler reports that the method needs the override modifier. The keyword also protects you from typos: override def bak() in a class whose parent has no bak fails with "method bak overrides nothing".
    • extends Dog(name) passes the constructor argument up. Puppy's parameter name is handed to Dog's constructor, where val name makes it a field. Inside Puppy, the plain parameter name is also available in method bodies.
    • The dog is untouched. The last driver line calls bark() on a plain Dog, which prints only Woof! I am Max. Overriding in Puppy changes nothing for Dog objects.

    Edge cases and common mistakes

    • Forgetting super.bark(). The output then has only the Yip! lines, and the Woof! line is missing for both puppies.
    • Calling bark() instead of super.bark(). Inside the override, a plain bark() calls the same method again. It never reaches the parent: the method calls itself until the program fails with a StackOverflowError. super. is what jumps to the parent's version.
    • Wrong order. Printing the puppy's line first gives the correct lines in the wrong order, which fails the output check.
    • Editing Dog instead of Puppy. Adding the Yip! line to Dog.bark() would make the plain dog print it too, and the last line of the expected output would no longer match.
    • Missing the s prefix. Without it, "Yip! Said $name" prints the text $name literally instead of the name.

    Testing

    Besides the lesson's driver, try the Loud and Quiet classes from the approach section. Quiet("Buddy").bark() prints Yip! Said Buddy, and Loud("Rex").bark() prints Woof! I am Rex twice.

    Now store a subclass object in a variable typed as the parent:

    val d: Dog = Quiet("Zed")
    d.bark()

    The output is Yip! Said Zed. The variable's declared type is Dog, but the method that runs belongs to the object, so the override wins. This is called dynamic dispatch, and it is what makes super useful: callers can use any Dog without knowing which subclass they hold, and each subclass decides whether to extend or replace the parent's behaviour.

    Chains of parents

    super always means the nearest parent, and that parent's own method may call its parent in turn. With three levels, each override adds one line on top of the previous one:

    class Animal { def describe(): Unit = println("An animal") }
    class Dog2 extends Animal {
        override def describe(): Unit = { super.describe(); println("A dog") }
    }
    class Puppy2 extends Dog2 {
        override def describe(): Unit = { super.describe(); println("A puppy") }
    }

    Calling describe() on a Puppy2 prints three lines:

    An animal
    A dog
    A puppy

    Puppy2 asks Dog2, which asks Animal. The innermost call finishes first, so the lines come out from the oldest ancestor down to the newest subclass. Putting the super call last instead would reverse that order, which shows why the position of the call is a real design choice and not a detail.

    Key takeaways

    • Overriding replaces the parent's method; super.method() brings the parent's behaviour back in.
    • Put the super call where the parent's work should happen: before, after or between your own code.
    • Scala requires override when you redefine an inherited method.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free