Redefining the inherited function in a child class is called overriding. The purpose of function-overriding is to allow the derived class to give its own implementation because the provided implementation is not sufficient. In Kotlin, there are few rules to override a function:
- The function in the parent class must be declared open
- The function in the child class must use the override keyword
Let's add the displayInfo() function in the Student class and include more information using the print function. This works as follows:
open class Person(pName: String, pAge: Int) {
var name = pName
var age = pAge
open fun displayInfo(){
println("My name is $name, I am $age years old.")
}
}
class Student(name: String, age: Int, id : Int, education : String, institution : String) : Person(name , age ) {
var studentID = id
val institutionName = institution
val education = education
override fun displayInfo() {
println("My name is $name, I am $age old. " +
"I am a student of $education in $institutionName and my ID is $studentID")
}
}
The Student class now contains its own displayInfo() function with all its properties included. This function overrides the function declared in the Person class. The Person class has to open the displayInfo() function and the Student class can then override it:
fun main(args: Array<String>) {
val p = Person(pName = "Jon",pAge = 35)
p.displayInfo()
val bob = Student(name = "Bob Peter", age = 25,
id = 100, education = "Computer programming", institution = "Stockholm University")
bob.displayInfo()
}
The output shown here looks more like what we would expect. The Person object calls the displayInfo() function of the Person class, and the Student class object calls the function of its own class because the displayInfo() function is overridden:
In the new implementation, the overridden function contains additional information about the student's education and institute, but there is some code repetition. If we compare both the displayInfo() functions, we can see that the name and age information is displayed in both functions. This is not a good programming technique. When the overridden function does not require a completely different implementation, it is always a good idea to call the parent class function to the child class.