定义类
class MyObject private constructor(name: String, age: Int) { private var name: String private var age: Int = 0 init { this.name = name this.age = age println("init in MyObject called") } constructor() : this("Null", 111) { println("constructor() in MyObject called") } fun setName(name: String) { this.name = name } fun getName(): String { return name } fun setAge(age: Int) { this.age = age } fun getAge(): Int { return age } }
该类中,主构造器是constructor(name: String, age: Int),次构造器是constructor()
主构造器中不能包含代码,初始化代码可以写在init { }中,次构造器可以有多个
创建类的实例,例如
val frame = JFrame("窗口")
继承
import javax.swing.JFrame class MainFrame(title: String) : JFrame(title) { init { setSize(300, 200) setLocationRelativeTo(null) defaultCloseOperation = EXIT_ON_CLOSE } constructor() : this("未标题") } fun main(args: Array<String>) { MainFrame("主窗口").isVisible = true val mainFrame = MainFrame() mainFrame.setSize(400, 300) mainFrame.isVisible = true }
MainFrame继承JFrame,主构造器constructor(String),调用了基类构造JFrame(String)
参考链接:Kotlin 继承 | 菜鸟教程