Noob question here, I am working my way through a Udemy beginner Kotlin course and I can't work out why my age parameter isn't used when I use my derived class, but will work when my base class is used.
Person Class
open class Person(open var firstname: String, open var surname: String,
open var age: Int) {
val thisyear: Int = Calendar.getInstance().get(Calendar.YEAR)
val dob = thisyear - age
fun printperson() {
println("$firstname $surname was born in $dob")
}
}
Student Class
class Student(override var firstname: String, override var surname:
String, override var age: Int, val studentID: Int):
Person(firstname, surname, age) {
fun returnDetails() {
println("Hello $firstname, your Student ID is: $studentID")
}
}
Main
fun main(args: Array<String>) {
val studentMike = Student(firstname = "Mike",
surname = "Stand", age = 67, studentID = 8899)
studentMike.printperson()
studentMike.returnDetails()
val personBill = Person(firstname = "Bill", surname = "Hook", age = 34)
personBill.printperson()
}
Output
Mike Stand was born in 2018
Hello Mike, your Student ID is: 8899
Bill Hook was born in 1984
As you can see Bill was a direct use of the method in the Person Class, whereas Mike was an indirect call, the age parameter should have been inherited from the Person Class through the Student Class...
Looking at the official Kotlin docs, it looks like the issue is to do with the "Derived class initialisation order" but for the life of me I can't quite grok how to correct this.
Thanks for your help,
PS apologies for the inaccurate terminology. Always glad of pointers to do better.