How to Use Inheritance in Kotlin: Syntax and Examples
In Kotlin, use
open keyword on a class to allow inheritance and : to extend it. Override functions with override keyword to customize behavior in the child class.Syntax
To use inheritance in Kotlin, mark the parent class with open to allow other classes to inherit from it. Use : after the child class name to extend the parent class. Override functions or properties with the override keyword.
- open class Parent: Allows inheritance.
- class Child : Parent(): Child inherits from Parent.
- override fun: Customize parent behavior.
kotlin
open class Parent { open fun greet() { println("Hello from Parent") } } class Child : Parent() { override fun greet() { println("Hello from Child") } }
Example
This example shows a parent class Animal with an open function sound(). The child class Dog inherits from Animal and overrides sound() to provide its own message.
kotlin
open class Animal { open fun sound() { println("Some generic animal sound") } } class Dog : Animal() { override fun sound() { println("Bark") } } fun main() { val myAnimal: Animal = Dog() myAnimal.sound() // Calls Dog's sound() }
Output
Bark
Common Pitfalls
Common mistakes include forgetting to mark the parent class as open, which causes a compilation error when trying to inherit. Also, forgetting to use override when redefining functions leads to errors. Lastly, constructors must be called properly in the child class.
kotlin
/* Wrong: Parent class not open */ class Parent { fun greet() { println("Hello") } } // class Child : Parent() {} // Error: Cannot inherit from final class /* Correct: Mark parent as open and override */ open class ParentOpen { open fun greet() { println("Hello") } } class Child : ParentOpen() { override fun greet() { println("Hi") } }
Quick Reference
| Concept | Syntax | Description |
|---|---|---|
| Allow inheritance | open class Parent | Marks class as inheritable |
| Inherit class | class Child : Parent() | Child inherits from Parent |
| Override function | override fun func() | Customize parent function |
| Call parent constructor | class Child(param: Type) : Parent(param) | Pass arguments to parent |
| Final class | class Parent | Cannot be inherited unless open |
Key Takeaways
Mark parent classes with open to allow inheritance.
Use : to extend a parent class in Kotlin.
Override parent functions with override keyword.
Always call the parent constructor if it requires parameters.
Forgetting open or override keywords causes compile errors.