Sobes.tech
Junior

How does inheritance work in Kotlin?

sobes.tech AI

Answer from AI

Inheritance in Kotlin is based on the principle of open classes. By default, all classes are closed (final), and to make a class inheritable, it must be explicitly marked with the open keyword.

Main points:

  • Open classes: The parent class must be marked as open.
    open class Base {
        // ...
    }
    
  • Inheritance: Inheritance is done using a colon (:), followed by the parent class name and, if necessary, a call to its constructor.
    class Derived : Base() {
        // ...
    }
    
  • Overriding methods and properties: To override methods or properties of the parent class, they must be marked as open in the parent, and the override keyword must be used in the child.
    open class Base {
        open fun process() { /* ... */ }
        open val value: Int = 0
    }
    
    class Derived : Base() {
        override fun process() { /* ... */ }
        override val value: Int = 1
    }
    
    If the parent method or property is not marked as open, it cannot be overridden.
  • Access to parent class members: Access to parent class members from the child is done using the super keyword.
    class Derived : Base() {
        override fun process() {
            super.process() // Call to parent class method
            // ...
        }
    }
    
  • Constructors: If the parent class has a constructor with parameters, the child class must call this constructor in its signature.
    open class Base(name: String) {
        // ...
    }
    
    class Derived(name: String, age: Int) : Base(name) {
        // ...
    }
    
  • Interfaces: A class can implement multiple interfaces, which are specified after the class it inherits from, separated by commas. Interfaces are open for implementation by default.
    interface MyInterface {
        fun doSomething()
    }
    
    class MyClass : Base(), MyInterface {
        override fun doSomething() { /* ... */ }
    }
    
  • Abstract classes: Abstract classes are used to define partial implementations and contain abstract methods and properties (marked with abstract) that must be implemented in subclasses. Abstract members do not require open. An abstract class also does not require open for inheritance.
    abstract class AbsBase {
        abstract fun abstractMethod()
        open fun concreteMethod() { /* ... */ }
    }
    
    class AbsDerived : AbsBase() {
        override fun abstractMethod() { /* ... */ }
    }
    

Overall, Kotlin emphasizes explicitness, requiring the use of open for inheritance and overriding.