Open keyword in Kotlin
In Kotlin, we can mark a class, a function, or a variable with the open keyword.
Let's understand why we use the open keyword in Kotlin.
Open keyword with class
The open keyword with the class indicates that the class is open for extension, which means we can create a subclass of that open class.
In Kotlin, all classes are final by default, which means they cannot be inherited.
Suppose we have a class Person. We will not be able to create a subclass of the class. The compiler will show an error.
open keyword with variable
Similarly, the variables in Kotlin are final by default. So, to override it in the child class, we need to set the variables as open in our base class.
Here is the base class Person and its child class. We will not be able to override the variable. It shows the error below.
open keyword with function
Similar to the classes, all the functions in Kotlin are by default, final, meaning that you can't override a function.
Consider a function Information() inside the Person class. We will not be able to override the function.
Again, in Kotlin, all variables, classes, and functions are by default final, whereas in Java, the opposite is true. In Java, we must use the final keyword to make the variable final.
That is why we need the open keyword in Kotlin with the variable, classes and functions to allow it to be overridden.