Hierarchical inheritance

A situation in which a parent class is inherited by many subclasses is called hierarchical inheritance. This is shown in the following diagram, where A is a parent class and B, C, and D are child classes. In this inheritance model, two or more classes are derived from the parent class:

Create a superclass, Person, and two derived classes, Student and Employee:

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.")
}
}
fun main(args: Array<String>) {

val bob = Student("Bob", "Peter", 25, "A-123")
bob.speak()
bob.greet()
bob.attendLectures()
bob.aboutEducation()
}

The Person class contain four properties—first name, last name, age, and ID. It also contains two functions. The student class inherits all properties and behaviors from the Person class and has its own functions. Both classes share properties from their parent class. 

A complete example can be found on GitHub: https://github.com/PacktPublishing/Hands-On-Object-Oriented-Programming-with-Kotlin/tree/master/src/main/kotlin/Chapter03.

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

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