In Kotlin, classes are final by default to keep code safe and clear. The open keyword lets you say a class can be inherited, making it easy to extend and reuse code.
0
0
Why open keyword is required for inheritance in Kotlin
Introduction
When you want to create a base class that others can build on.
When you need to add new features to an existing class by making a child class.
When designing a framework or library where users can customize behavior by inheritance.
Syntax
Kotlin
open class BaseClass { // class body } class ChildClass : BaseClass() { // child class body }
Without open, a class cannot be inherited.
Use open only when you want to allow inheritance to keep code safe.
Examples
The
Animal class is open, so Dog can inherit from it.Kotlin
open class Animal { fun sound() = "Some sound" } class Dog : Animal() { fun bark() = "Woof" }
Car is not open, so SportsCar cannot inherit from it.Kotlin
class Car { fun drive() = "Driving" } // This will cause an error: // class SportsCar : Car() {}
Sample Program
This program shows a base class Vehicle marked as open. The Bike class inherits from it and adds a new function. We create a Bike object and call both functions.
Kotlin
open class Vehicle { fun start() = "Vehicle started" } class Bike : Vehicle() { fun ringBell() = "Ring ring!" } fun main() { val bike = Bike() println(bike.start()) println(bike.ringBell()) }
OutputSuccess
Important Notes
Marking classes as final by default helps avoid unexpected changes in large projects.
You can also mark functions and properties as open to allow overriding.
Summary
Kotlin classes are final by default to keep code safe.
The open keyword allows a class to be inherited.
Use open only when you want to allow others to extend your class.