class Teacher{
var name : String = _ //占位符
private var age = 27 // 默认生成私有的setter、getter
private[this] val gender = "male"
//重载构造器
def this(name : String){
this //主构造器
this.name = name
}
//重载构造器必须调用主构造器
def sayHello(){
println(this.name + ":" + this.age + ":" + this.gender);
}
}
//构造器具有参数,这些参数会成为属性
class Teacher private (val name : String, val age : Int){//private修饰后,主构造器将不能被调用
println("This is the primary constructor!!!")
var gender : String = _
println(gender)
//构造时,除了方法,其他都会被实例化,所以以上步骤会执行
def this(name : String, age : Int, gender : String){
this(name, age)
this.gender = gender
}
}
网友评论