The final keyword

Let's create another child class, Alien, and extend it from the Student class. Override the displayInfo function and add a print message:

class Alien (name: String, age: Int, id : Int, education : String, institution : String): Student(name, age, id, education, institution){
override fun displayInfo() {
super.displayInfo()
println("I know everything")
}
}
fun main(args: Array<String>) {

val alien = Alien(name = "Alien eli", age = 225,
id = 10101, education = "Computer Virus", institution = "Pluto")
alien.displayInfo()
}

Don't forget to open the Student class so that the Alien class can extend it. However, we can see that we don't need to add the open keyword with the displayInfo() function in the Student class. Once the function in a parent class is open for overriding, it is available for the complete hierarchy, but we may want to restrict this function at a particular level. For example, if we want the displayInfo() function of the Student class to be a final implementation so that no child class can override it, we can do that by adding the final keyword in the function signature. Let's restrict the displayInfo function at the level of the Student class:

open class Student(name: String, age: Int, id : Int, education : String, institution : String) : Person(name , age ) {
override final fun displayInfo() {
super.displayInfo()
println("I am a student of $education in $institutionName and
my ID is
$studentID")
}
}

As soon as displayInfo in the Student class is declared final, the Kotlin compiler will throw the following error in the Alien class:

Kotlin: 'displayInfo' in 'Student' is final and cannot be overridden.

We must remove the displayInfo function from the Alien class to compile the code.

The final keyword restricts the child class from overriding the function, but the child class can still access the function of the parent class.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.131.212