【问题标题】:Kotlin constructor with super class具有超类的 Kotlin 构造函数
【发布时间】:2016-03-28 00:40:58
【问题描述】:

无论我尝试的任何方式,无论是主构造函数还是辅助构造函数,我都无法弄清楚如何在 kotlin 中声明一个具有超类和构造函数的新类。

class myPanel : JPanel {
    myPanel() : super() {

    }
}

这是我最想这样做的,但它给出了一个期望成员声明的错误。

class myPanel() : JPanel() {
    {
        ...
    }
}

这就是我认为主构造函数的外观,但它给出了相同的错误。搜索互联网并没有帮助,我只能找到第二个示例。

那么,创建具有超类及其一个构造函数的类的所有有效方法是什么?

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    Kotlin 的构造函数包含在 init 块中

    class Test : SuperClass() {
        init {
          // Do constructor stuff here
        }
    }
    

    更多信息可以在 Kotlin 的类参考中找到:https://kotlinlang.org/docs/reference/classes.html#constructors

    【讨论】:

    • 谢谢,原来我只需要更多地筛选文档:/
    【解决方案2】:

    除了上面的答案。 如果超类有任何参数这样传递,

    class Dog(name: String, color: String): Animal(name, color){
        init {
            // Do Constructor tasks here...
        }
    }
    

    【讨论】:

    • 谢谢你,帮了我很多忙
    【解决方案3】:

    你可以使用初始化

    class Test : Parent Class(){
    init {
       //your code goes here
        }
    }
    

    【讨论】:

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