Explain how the 'super' keyword works in Kotlin?
sobes.tech AI
Answer from AI
The keyword super is used to access members (properties, methods) of the parent class from a child class.
Main usage scenarios:
-
Calling the constructor of the parent class: Often used in the constructor of a child class to call the corresponding constructor of the parent. This is mandatory if the parent class has a primary constructor with parameters.
open class Parent(val name: String) class Child(name: String) : Parent(name) { // Child's constructor calls Parent's constructor, // passing the parameter name. } -
Accessing members of the parent class overridden in the child: Allows you to refer to the implementation of a method or property in the parent class, even if they have been overridden (using
override) in the child.open class Base { open fun greet() { println("Hello from Base") } open val value: Int = 1 } class Derived : Base() { override fun greet() { super.greet() // Call greet() from Base println("Hello from Derived") } override val value: Int = 2 get() { println("Accessing Derived value") return super.value + 1 // Access to value from Base } } -
Accessing members of a specific supertype (in case of multiple interface inheritance): If a class implements multiple interfaces that have members with the same names,
supercombined with specifying the interface name in angle brackets (super<TypeName>) allows unambiguous reference to a member of a specific interface.interface MyInterface1 { fun foo() { println("MyInterface1 foo") } } interface MyInterface2 { fun foo() { println("MyInterface2 foo") } } class MyClass : MyInterface1, MyInterface2 { override fun foo() { super<MyInterface1>.foo() // Call foo() from MyInterface1 super<MyInterface2>.foo() // Call foo() from MyInterface2 } }