Beginner question - Inheritance - why isn't my age constructor parameter used?

前端 未结 2 666
挽巷
挽巷 2020-12-22 05:40

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 w

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-22 06:39

    the documentation you are referring to, says explicitly "When designing a base class, you should therefore avoid using open members in the constructors, property initializers, and init blocks"

    this is exactly what is happening in your example. In the base class Person you use the open member age in the constructor (the line where you calculate the dob). This should be avoided because when that line calculating dob is executed, age did not yet receive a value from the derived class.

    Ok, I did not answer at the "How to correct this?" but I hope it helps in clarifying what is going on

提交回复
热议问题