0
0
Kotlinprogramming~20 mins

Open classes and methods in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Open Classes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of overriding an open method
What is the output of this Kotlin code?
Kotlin
open class Animal {
    open fun sound() = "Some sound"
}

class Dog : Animal() {
    override fun sound() = "Bark"
}

fun main() {
    val animal: Animal = Dog()
    println(animal.sound())
}
ARuntime error
BBark
CCompilation error
DSome sound
Attempts:
2 left
💡 Hint
Remember that open methods can be overridden in subclasses.
Predict Output
intermediate
2:00remaining
Effect of missing open keyword on inheritance
What happens when you try to compile and run this Kotlin code?
Kotlin
class Vehicle {
    fun drive() = "Driving"
}

class Car : Vehicle() {
    override fun drive() = "Car driving"
}

fun main() {
    val car = Car()
    println(car.drive())
}
ACompilation error: 'drive' in 'Vehicle' is final and cannot be overridden
BDriving
CCar driving
DRuntime error
Attempts:
2 left
💡 Hint
Check if the method drive() is open for overriding.
🔧 Debug
advanced
2:00remaining
Why does this override fail?
This Kotlin code fails to compile. What is the reason?
Kotlin
open class Parent {
    fun greet() = "Hello"
}

class Child : Parent() {
    override fun greet() = "Hi"
}
AParent class must be abstract to allow overrides
BChild class must be open to override methods
CMissing override keyword causes error
Dgreet() in Parent is not open, so it cannot be overridden
Attempts:
2 left
💡 Hint
Check the declaration of greet() in Parent.
🧠 Conceptual
advanced
1:30remaining
Open classes and inheritance behavior
Which statement about open classes and methods in Kotlin is true?
AClasses and methods are open by default, so they can be inherited and overridden without keywords
BOnly classes are final by default; methods are open by default
CClasses and methods are final by default; you must mark them open to allow inheritance or overriding
DYou cannot inherit from open classes
Attempts:
2 left
💡 Hint
Think about Kotlin's default behavior for classes and methods.
Predict Output
expert
2:30remaining
Output with open class and method with property override
What is the output of this Kotlin program?
Kotlin
open class Person {
    open val greeting: String = "Hello"
    open fun greet() = greeting
}

class Student : Person() {
    override val greeting: String = "Hi"
    override fun greet() = "${greeting}, student!"
}

fun main() {
    val p: Person = Student()
    println(p.greet())
}
AHi, student!
BCompilation error
CHello
DHello, student!
Attempts:
2 left
💡 Hint
Remember that properties can be overridden and used in methods.