Overriding

Inheritance is a method in which a child class can access all the functions and properties of its parent class. What if, however, the derived class wants its own specific implantation of the function that is already provided by the derived class? To understand this problem, let's take a simple example of a Person class with two properties, name and age, and a function, displayInfo():

open class Person(pName: String, pAge: Int) {
var name = pName
var age = pAge

fun displayInfo(){
println("My name is $name, I am $age old. ")
}
}

Create another class called Student with some extra properties (id, education, and institute name) and extend it with the Person class:

class Student(name: String, age: Int, id : Int, education : String, institution : String) : Person(name , age ) {
var studentID = id
val institutionName = institution
val education = education
}

All the properties and functions of the Person class are part of the Student class. Create an object of the Person and Student classes and call the displayInfo() function:

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 of this code block is as follows:

My name is Jon, I am 35 old.
My name is Bob Peter, I am 25 old.

The output of the Person class looks fine, but the output of the Student class is not as expected. We don't have any information about their education, institution, or ID. When a parent class function does not fulfill the requirements of the child class, it is necessary to rewrite it.

..................Content has been hidden....................

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