0
0
Kotlinprogramming~10 mins

Why open keyword is required for inheritance in Kotlin - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a class that can be inherited.

Kotlin
open class Animal {
    fun sound() {
        println("Animal sound")
    }
}

class Dog : [1]() {
}
Drag options to blanks, or click blank then click option'
Afun
Bopen
Cclass
DAnimal
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'open' instead of the class name after the colon.
Forgetting to specify the parent class name.
2fill in blank
medium

Complete the code to allow the function to be overridden in a subclass.

Kotlin
open class Vehicle {
    open fun drive() {
        println("Driving vehicle")
    }
}

class Car : Vehicle() {
    override fun [1]() {
        println("Driving car")
    }
}
Drag options to blanks, or click blank then click option'
AVehicle
Bopen
Cdrive
Doverride
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'open' or 'override' as the function name.
Changing the function name in the subclass.
3fill in blank
hard

Fix the error by adding the required keyword to allow inheritance.

Kotlin
class Person {
    fun greet() {
        println("Hello")
    }
}

class Student : [1]() {
}
Drag options to blanks, or click blank then click option'
APerson
Bopen Person
Copen
DPerson open
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to inherit from a class not marked as open.
Adding 'open' in the wrong place.
4fill in blank
hard

Fill both blanks to create an open class and override its function.

Kotlin
class [1] {
    fun greet() {
        println("Hi")
    }
}

class Friend : [2]() {
    override fun greet() {
        println("Hello friend")
    }
}
Drag options to blanks, or click blank then click option'
Aopen Friend
BFriend
Copen Person
DPerson
Attempts:
3 left
💡 Hint
Common Mistakes
Not marking the base class as open.
Trying to override a function without the base function being open.
5fill in blank
hard

Fill all three blanks to define an open class, an open function, and override it in a subclass.

Kotlin
class [1] {
    [2] fun speak() {
        println("Speaking")
    }
}

class Teacher : [3]() {
    override fun speak() {
        println("Teaching")
    }
}
Drag options to blanks, or click blank then click option'
Aopen Person
Bopen
CPerson
DTeacher
Attempts:
3 left
💡 Hint
Common Mistakes
Not marking the function as open.
Not marking the base class as open.