How to Extend Existing Class in Kotlin: Simple Guide
In Kotlin, you extend an existing class by creating a new class with a
: followed by the parent class name and parentheses for the constructor. Use the open keyword on the parent class to allow inheritance, and override functions with override keyword if needed.Syntax
To extend a class in Kotlin, the parent class must be marked with open to allow inheritance. The child class uses a colon : followed by the parent class name and constructor arguments. You can override functions using the override keyword.
- open class Parent(val name: String): Allows the class to be inherited.
- class Child(name: String) : Parent(name): Child class extends Parent.
- override fun functionName(): Overrides a function from the parent.
kotlin
open class Parent(val name: String) { open fun greet() { println("Hello from $name") } } class Child(name: String) : Parent(name) { override fun greet() { println("Hi, I am $name, child class here!") } }
Example
This example shows how to extend a class Parent and override its function greet. The child class Child changes the greeting message.
kotlin
open class Parent(val name: String) { open fun greet() { println("Hello from $name") } } class Child(name: String) : Parent(name) { override fun greet() { println("Hi, I am $name, child class here!") } } fun main() { val parent = Parent("ParentClass") parent.greet() val child = Child("ChildClass") child.greet() }
Output
Hello from ParentClass
Hi, I am ChildClass, child class here!
Common Pitfalls
Common mistakes include forgetting to mark the parent class as open, which causes a compilation error when trying to inherit. Another mistake is not using override when redefining a function, which also causes errors.
Also, remember to call the parent constructor properly if it requires parameters.
kotlin
/* Wrong: Parent class not open */ class Parent(val name: String) { fun greet() { println("Hello from $name") } } // Trying to extend this will cause error // class Child(name: String) : Parent(name) {} /* Correct: Parent class open and override used */ open class ParentOpen(val name: String) { open fun greet() { println("Hello from $name") } } class ChildCorrect(name: String) : ParentOpen(name) { override fun greet() { println("Hi, I am $name") } }
Quick Reference
- open class Parent: Make class inheritable.
- class Child : Parent(): Extend parent class.
- override fun function(): Override parent function.
- Call parent constructor with parameters if needed.
Key Takeaways
Mark the parent class with open to allow inheritance.
Use colon (:) to extend the parent class and call its constructor.
Override functions with the override keyword to change behavior.
Always call the parent constructor if it has parameters.
Forgetting open or override keywords causes compile errors.