【问题标题】:more parameters in constructor of subclass in kotlinkotlin子类的构造函数中的更多参数
【发布时间】:2018-11-16 20:23:14
【问题描述】:

我是新手。 我想在从 Person 类驱动的 Employee 类中添加年龄参数。我怎么能在 kotlin 中做到这一点?!

abstract class Person constructor (var name :String ,var gender :String) {
}

我用这种方式出错了:

class Employee() : Person() {
    constructor(age : Int ) : super (name , gender)
} 

为什么不能在Employee构造函数中使用var或val?! 我的错误是什么?

【问题讨论】:

    标签: kotlin constructor class-constructors


    【解决方案1】:

    为此使用主构造函数:

    class Employee(name: String, gender: String, val age: Int) : Person(name, gender) {} 
    

    当你在父类中有一个带有一些参数的主构造函数时,你应该在它的子类中指定相同的构造函数,并在需要时加上额外的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-19
      • 2021-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 2021-07-05
      相关资源
      最近更新 更多