object class01 { // 特点:名字就叫this。它的代码的第一行必须是调用主构造器。可以有多个。 class Student(var name: String, var age: Int) { println("Student构造函数被调用....")
// 辅助构造函数1
def this(name: String) {
this(name, 15)
println("辅助构造函数被调用....")
}
// 辅助构造函数2
def this(age: Int) {
this("未知", age)
println("辅助构造函数被调用....")
}
def sayHello(): Unit = {
println(s"我是${name},今年${age}")
}
}
def main(args: Array[String]): Unit = { // 实例化类的对象 stu // new 的时候,就会自动调用一次构造函数 val stu = new Student("小花", 18) // 调用对象的方法 stu.sayHello()
val stu1 = new Student("小明")
stu1.sayHello()
val stu2 = new Student(20)
stu2.sayHello()
} }