open class Person (open val name: String = "", open var age: Int) { init {} open fun greeting(pn: String) { println("$name says hello to $pn") } } class Student(override val name: String, override var age: Int = 18, val studentID: Long): Person(name, age) { override fun greeting(pn: String) { println("$name, $studentID says hello to $pn") } } fun main() { val p = Student(age=23, name="Jack", studentID=1234586L) p.greeting("Wan") // Jack, 1234586 says hello to Wan }
Kotlin is very strict for inheritance, for the parent class, we have to add open keyword to the class and its methods and properties we want to extend.
For the child class, we have to add override keywrod for the functions and properties we want to override.