0
0
Kotlinprogramming~5 mins

Open classes and methods in Kotlin

Choose your learning style9 modes available
Introduction

In Kotlin, classes and methods are closed by default. You use open to allow other classes to change or add behavior by inheriting or overriding.

When you want to create a base class that others can build upon.
When you want to change how a method works in a child class.
When you want to add new features by extending existing classes.
When you want to reuse code but customize some parts.
When you want to design flexible and reusable software.
Syntax
Kotlin
open class ClassName {
    open fun methodName() {
        // method body
    }
}

Use open before class to allow inheritance.

Use open before fun to allow overriding in subclasses.

Examples
This class can be inherited and its sound method can be changed.
Kotlin
open class Animal {
    open fun sound() {
        println("Some sound")
    }
}
The Dog class changes the sound method to print "Bark".
Kotlin
class Dog : Animal() {
    override fun sound() {
        println("Bark")
    }
}
The Cat class inherits Animal but does not change the sound method.
Kotlin
class Cat : Animal() {
    // Uses the original sound method
}
Sample Program

This program shows a base class Vehicle with an open method drive. The Car class inherits Vehicle and changes the drive method. The output shows how each class behaves.

Kotlin
open class Vehicle {
    open fun drive() {
        println("Driving vehicle")
    }
}

class Car : Vehicle() {
    override fun drive() {
        println("Driving car")
    }
}

fun main() {
    val myVehicle = Vehicle()
    myVehicle.drive()

    val myCar = Car()
    myCar.drive()
}
OutputSuccess
Important Notes

If you forget open, you cannot inherit or override.

Mark only classes and methods open that you want to extend or change.

Use override keyword when changing a method in a subclass.

Summary

Classes and methods are closed by default in Kotlin.

Use open to allow inheritance and overriding.

Use override to change behavior in subclasses.