Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin Inheritance

Inheritance is one of the key principles of object-oriented programming. It allows for creating a new class based on an existing class, inheriting attributes and behaviors (properties and methods) from the base class.

Kotlin treats inheritance a bit differently than some other popular OOP languages. Here's a tutorial on Kotlin's approach to inheritance:

1. Open Classes:

Unlike Java, in Kotlin, all classes are final by default, meaning you can't inherit from them. If you want to allow a class to be subclassed, you need to declare it as open.

open class BaseClass {
    fun baseFunction() {
        println("Base function")
    }
}

2. Inheriting from a Base Class:

Once a class is marked open, you can inherit from it using the : symbol.

class DerivedClass : BaseClass()

Now, DerivedClass has access to methods and properties of BaseClass.

3. Overriding Methods and Properties:

Just as classes are final by default, so are their member functions and properties. If you want to allow a method or property to be overridden, you need to mark it with the open keyword in the base class. In the derived class, use the override keyword.

open class BaseClass {
    open fun functionToOverride() {
        println("Base implementation")
    }
}

class DerivedClass : BaseClass() {
    override fun functionToOverride() {
        println("Derived implementation")
    }
}

4. Calling the Super Class Implementation:

You can call the base class's implementation of an overridden method using the super keyword.

class DerivedClass : BaseClass() {
    override fun functionToOverride() {
        super.functionToOverride()
        println("Additional behavior in derived class")
    }
}

5. Primary Constructor Inheritance:

If the base class has a constructor, the derived class must initialize the base class using the primary constructor:

open class BaseClass(val message: String)

class DerivedClass(message: String) : BaseClass(message)

6. Secondary Constructor Inheritance:

If you're using secondary constructors in the derived class, you must either call the primary constructor of the derived class or directly call the base class's constructor using super.

class DerivedClass : BaseClass {
    constructor(message: String, anotherParameter: Int) : super(message) {
        // some initialization
    }
}

7. Abstract Classes:

Abstract classes are open by default and cannot be instantiated. They can contain abstract methods that don't have an implementation and must be overridden in derived classes.

abstract class AbstractBase {
    abstract fun abstractFunction(): String
}

class ConcreteClass : AbstractBase() {
    override fun abstractFunction() = "Implemented!"
}

8. Interfaces:

Kotlin supports multiple inheritances through interfaces. You can declare properties and methods in interfaces, and classes can implement multiple interfaces.

interface InterfaceA {
    fun functionA()
}

interface InterfaceB {
    fun functionB()
}

class MultiClass : InterfaceA, InterfaceB {
    override fun functionA() {
        println("Implement A")
    }

    override fun functionB() {
        println("Implement B")
    }
}

Conclusion:

Inheritance in Kotlin ensures more safety and predictability by being explicit about which classes and members can be extended or overridden. This is achieved through the use of the open, abstract, and override keywords. By understanding these concepts, you can design robust Kotlin applications with clear and maintainable object-oriented structures.

  1. Single inheritance in Kotlin:

    • Kotlin supports single inheritance, where a class can inherit from only one superclass.
    open class Animal
    
    class Dog : Animal()
    
  2. Subclassing and superclass in Kotlin:

    • Create a subclass by inheriting from a superclass.
    open class Shape
    class Circle : Shape()
    
  3. Overriding methods in Kotlin:

    • Override methods in subclasses for customized behavior.
    open class Shape {
        open fun draw() {
            println("Drawing a shape")
        }
    }
    
    class Circle : Shape() {
        override fun draw() {
            println("Drawing a circle")
        }
    }
    
  4. Using 'open' keyword for inheritance in Kotlin:

    • Use the open keyword to allow subclasses to inherit and override.
    open class Shape {
        open fun draw() {
            println("Drawing a shape")
        }
    }
    
  5. Inheritance vs composition in Kotlin:

    • Choose between inheritance and composition based on design preferences.
    // Inheritance
    open class Engine
    
    class Car : Engine()
    
    // Composition
    class Car(private val engine: Engine)
    
  6. Constructors in inherited classes in Kotlin:

    • Call the superclass constructor in the subclass.
    open class Shape(val color: String)
    
    class Circle(color: String, val radius: Double) : Shape(color)
    
  7. Visibility modifiers in Kotlin inheritance:

    • Use visibility modifiers (private, protected, internal, public) in inherited members.
    open class Shape {
        protected val size = 10
    }
    
    class Circle : Shape() {
        fun getSize() = size
    }
    
  8. Abstract classes in Kotlin:

    • Declare abstract classes with abstract methods.
    abstract class Shape {
        abstract fun draw()
    }
    
    class Circle : Shape() {
        override fun draw() {
            println("Drawing a circle")
        }
    }
    
  9. Interfaces and multiple inheritance in Kotlin:

    • Achieve multiple inheritance using interfaces.
    interface Colorable {
        fun getColor(): String
    }
    
    open class Shape
    
    class ColoredCircle : Shape(), Colorable {
        override fun getColor(): String {
            return "Red"
        }
    }
    
  10. When to use inheritance in Kotlin:

    • Use inheritance when there is a clear "is-a" relationship between classes.
    open class Animal
    class Dog : Animal()
    
  11. Inheritance hierarchy in Kotlin projects:

    • Design a clear and manageable inheritance hierarchy.
    open class Vehicle
    class Car : Vehicle()
    class Bike : Vehicle()