Using the open keyword

To open classes in Kotlin, we can add the open keyword at the beginning of the superclass signatures:

open class Person (val fName: String, var lName: String, var pAge: Int, val ID : String) {

fun speak() {
println("My name is $fName $lName, my id is $ID and age is $pAge")
}

fun greet() {
println("Hi How are you...")
}
}

class Student(fName: String, lName: String, pAge: Int, ID: String ): Person(fName,lName,pAge, ID) {
fun aboutEducation(){
println("I am a student of Computer Science.")
}

fun attendLectures() {
println("I am studying Introduction to Kotlin lecture.")
}
}

Now, the Student child class has access to all the functions of the Person class, and has its own properties and functions as well. We will add two functions in the Student class—aboutEducation and attendLecture:

fun main(args: Array<String>) {
val bob = Student("Bob", "Peter", 25, "A-123")
bob.speak()
bob.greet()
bob.attendLectures()
bob.aboutEducation()
}

Once the object of the derived class is created, it can implicitly get access to all the functions and properties of its parent class:

Just like Student, we can also extend the Employee and Professor classes from the Person class.

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

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