Kotlin – Override Method
To override method of a Super class, define a function in the Child class with same definition as that of in Super class. Overriding a method of Super class is useful, when you need to change the default behaviour. Also note that only those functions that are open in Super class could be overridden.
Syntax – Kotlin Inheritance
The syntax to override method of a Parent class in Child class is
open class SuperClass(primary_constructor){
open fun behaviour_1(){
// common behaviour
}
}
class ChildClass(primary_constructor): SuperClass(primary_constructor_initialization){
fun behaviour_1(){
// custom behaviour overriding common behaviour
}
}
Note: The method to be overridden has to be open.
Example 1 – Override Method of Super Class in Kotlin
In the following example we shall define a super/parent class named Person
, and child class named Student
.
example.kt
fun main(args: Array<String>) {
var student_1 = Student("Arjun")
println("\n\nAbout "+student_1.name+"\n---------------")
student_1.doAll()
}
/**
* Person is a Super Class
*/
open class Person(var role: String = "Person", var name: String = "X") {
fun eat(){
println(name + " is eating.")
}
open fun sleep(){
println(name + " is sleeping.")
}
}
/**
* Student class inherits Person class
*/
class Student(name: String): Person("Student", name) {
// activity function belongs to Student only
fun activity(){
println("$name is a $role. $name is studying in school.")
}
// overrides sleep function of Person class
override fun sleep(){
println("$name is a $role. $name goes to bed early.")
}
fun doAll(){
eat()
sleep()
activity()
}
}
When the above program is run, you will get the following output.
Output
About Arjun
---------------
Arjun is eating.
Arjun is a Student. Arjun goes to bed early.
Arjun is a Student. Arjun is studying in school.
Conclusion
In this Kotlin Tutorial – Override Method of Super Class, we have learnt that the function that could be overridden has to be open, and the overriding function definition in Sub class has to be same as that of in Super class. We also saw a Kotlin Example to override method of super class.