Start learning free

LESSON 405 OF 414 · OBJECT-ORIENTED PROGRAMMING

Calling the Parent with super in Kotlin in Kotlin

Practice

TL ; DR:

Inside an override method, 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) : Dog(name) {
    override fun bark() {
        super.bark()   // do everything the parent did
        println("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("Yip! Said $name").

Notes:

  • In Kotlin a class can be extended only if it is open, and a method overridden only if it is open. Dog and Dog.bark are already marked that way.
  • Puppy(name: String) : Dog(name) passes the name to Dog's constructor; $name inside a string inserts the name property.

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

    Base Keyword in Kotlin

    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free