Scala中的构造器
Scala中的构造器
Scala中的构造器分为两类,主构造器和辅助构造器
主构造器是通过类名后面跟的括号里加参数列表来定义
辅助构造器是通过关键字this定义
定义一个无参主构造器
class rectangle(){
val width = 0
val height = 0
}
定义一个带参主构造器
class rectangle(w:Int){
val width = w
val height = 0
}
主构造器的函数体是在类里面的,可以说一个类里面除了方法和成员字段外都是主构造器的函数体,在类初始化的过程中会执行类体里面的语句。
可以在无参主构造器内这样定义和执行初始化方法
class rectangle(){
var width = 0
var height = 0
Init()
def Init(){
width = 1
height = 1
}
}
用this来定义辅助构造器,在辅助构造器里必须调用主构造器,所以说类的构造过程是必须经过主构造器。
注意
默认构造器是顺序执行的也就是从第一个非函数开发执行,所以如果你的上述代码是这样写的:
Init() var width = 0 var height = 0
width和height的值依然还是0!
辅助构造器一
class rectangle(){
var width = 0
var height = 0
def this(w:Int){
this()
width = w
}
}
辅助构造器二
class rectangle(){
var width = 0
var height = 0
def this(w:Int){
this()
width = w
}
def this(w:Int, h:Int){
this(w)
height = h
}
}
Keep it simple!
浙公网安备 33010602011771号