Kotlin构造函数与超级

Gra*_*mes 4 kotlin

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

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

    }
}
Run Code Online (Sandbox Code Playgroud)

这就是我最喜欢做的事情,但它给出了一个期待成员声明的错误.

class myPanel() : JPanel() {
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我认为主要构造函数看起来如何,但它给出了相同的错误.搜索互联网并没有帮助,我能找到的只是第二个例子.

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

Kis*_*kae 12

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

class Test : SuperClass() {
    init {
      // Do constructor stuff here
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Md *_*kib 10

除了以上答案.如果超类有任何参数像这样传递,

class Dog(name: String, color: String): Animal(name, color){
    init {
        // Do Constructor tasks here...
    }
}
Run Code Online (Sandbox Code Playgroud)