scala的主构造器(primary constructor)和辅助构造器(auxiliary constructor)
1.辅助构造器的名称为this
2.每个辅助构造器都必须直接或间接以主构造开始
—-辅助构造器
class Person {
private var name = ""
private var age = 0
// 一个辅助构造
def this(name:String) {
this()//调用主构造
this.name = name
}
// 另一个辅助
def this(name:String,age:Int){
// 调用另一个辅助构造
this(name)
this.age = age
}
}
调用
object Demo extends App{
val p1 = new Person("Bob",21)
val p2 = new Person("Jack")
val p3 = new Person
}
—主构造器
在scala中主构造不是用this方法定义的
//使用参数默认值
class Person(var name:String="",var age:Int=0){
// 主构造中的参数,如果在类中被使用,则会被当做字段来使用
override def toString = "name is "+name+" , age is "+age
}
调用主构造
object Demo extends App{
val p1 = new Person("Bob",21)
val p2 = new Person("Jack")
val p3 = new Person
//可以被看做字段
p3.name = "xxx"
p3.age = 100
println(p3.toString)
}
352

被折叠的 条评论
为什么被折叠?



