Challenge - 5 Problems
Open Classes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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()) }
Attempts:
2 left
💡 Hint
Remember that open methods can be overridden in subclasses.
✗ Incorrect
The method sound() is open in Animal and overridden in Dog. The variable animal holds a Dog instance, so calling sound() prints "Bark".
❓ Predict Output
intermediate2: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()) }
Attempts:
2 left
💡 Hint
Check if the method drive() is open for overriding.
✗ Incorrect
In Kotlin, methods are final by default. Since drive() is not marked open, overriding it causes a compilation error.
🔧 Debug
advanced2: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" }
Attempts:
2 left
💡 Hint
Check the declaration of greet() in Parent.
✗ Incorrect
Only methods marked open can be overridden. greet() is final by default, so override causes error.
🧠 Conceptual
advanced1:30remaining
Open classes and inheritance behavior
Which statement about open classes and methods in Kotlin is true?
Attempts:
2 left
💡 Hint
Think about Kotlin's default behavior for classes and methods.
✗ Incorrect
In Kotlin, classes and methods are final by default. You must explicitly mark them open to allow inheritance or overriding.
❓ Predict Output
expert2: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()) }
Attempts:
2 left
💡 Hint
Remember that properties can be overridden and used in methods.
✗ Incorrect
The Student class overrides greeting with "Hi" and greet() returns "Hi, student!". The variable p is a Person reference to a Student instance, so the overridden greet() runs.