Sobes.tech
Junior

Selgitage, kuidas töötab 'super' märksõna Kotlinis.

sobes.tech AI

Vastus AI-lt

The keyword super is used to access members (properties, methods) of the parent class from a child class.

Main usage options:

  1. Calling the parent class constructor: Often used in the child class constructor to invoke the corresponding parent constructor. 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 constructor calls Parent constructor,
        // passing the name parameter.
    }
    
  2. Accessing overridden members of the parent class: 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 class:

    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
            }
    }
    
  3. 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, super combined with specifying the interface name in angle brackets (super<TypeName>) allows unambiguously referring 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
        }
    }