Why Classes Are Final by Default in Kotlin Explained
In Kotlin, classes are
final by default to promote safer and more predictable code by preventing unintended inheritance. To allow a class to be inherited, you must explicitly mark it with the open keyword.Syntax
By default, Kotlin classes cannot be inherited because they are final. To allow inheritance, use the open keyword before the class name.
Example syntax:
class MyClass { }- final class, cannot be subclassed.open class MyOpenClass { }- open class, can be subclassed.
kotlin
class FinalClass { fun greet() = "Hello from final class" } open class OpenClass { open fun greet() = "Hello from open class" } class SubClass : OpenClass() { override fun greet() = "Hello from subclass" }
Example
This example shows that trying to inherit from a final class causes a compile error, while inheriting from an open class works fine.
kotlin
class FinalClass { fun greet() = "Hello from final class" } // Uncommenting the following line will cause a compile error: // class SubClass : FinalClass() {} open class OpenClass { open fun greet() = "Hello from open class" } class SubClass : OpenClass() { override fun greet() = "Hello from subclass" } fun main() { val obj = SubClass() println(obj.greet()) }
Output
Hello from subclass
Common Pitfalls
New Kotlin developers often try to inherit from classes without marking them open, causing compile errors. Another mistake is forgetting to mark overridden functions as open in the parent class, which prevents overriding.
Always remember:
- Classes are final by default.
- Functions must be
opento be overridden.
kotlin
open class Parent { // Missing 'open' keyword here causes error when overriding fun greet() = "Hello from parent" } class Child : Parent() { // Compile error: 'greet' in 'Parent' is final and cannot be overridden // override fun greet() = "Hello from child" } // Correct way: open class ParentCorrect { open fun greet() = "Hello from parent" } class ChildCorrect : ParentCorrect() { override fun greet() = "Hello from child" }
Quick Reference
| Keyword | Meaning |
|---|---|
| final (default) | Class or function cannot be inherited or overridden |
| open | Class or function can be inherited or overridden |
| override | Function overrides a parent open function |
Key Takeaways
Kotlin classes are final by default to prevent unintended inheritance.
Use the open keyword to allow a class or function to be inherited or overridden.
Functions must be marked open to be overridden in subclasses.
Trying to inherit from a final class causes a compile-time error.
Explicitly marking classes open makes your code safer and clearer.