Junior
How would you implement inheritance between two classes in Kotlin?
sobes.tech AI
Answer from AI
open class BaseClass {
// Base class, must be open for inheritance
fun baseMethod() {
// Method of the base class
}
}
class DerivedClass : BaseClass() {
// Derived class inherits from BaseClass using a colon
fun derivedMethod() {
// Method of the derived class
baseMethod() // Call to the base class method
}
}
In Kotlin, classes are closed (final) by default. To make a class inheritable, it must be marked with the open keyword. Inheritance is specified after the class name using a colon, followed by the name of the base class with parentheses (if there is a primary constructor).