val 修饰的属性是只读的,不能被修改
Student() 称 class Student()
1. 主构造函数(构造器),用来创建对象
2. 辅助构造函数,提供更多的方式来创建对象
package level02
class Student(var name: String, val age: Int) {
println("Student.........")
def this() = {
this("未知的", 18)
println("辅助构造器被调用了...")
}
def this(age: Int) = {
this("未知的", age)
}
def sayHi(): Unit = {
println(s"我是${name},我今年${age}")
}
}
object Class01 {
def main(args: Array[String]): Unit = {
val stu1 = new Student("小花", 18)
val stu2 = new Student()
val stu3 = new Student(20)
stu1.sayHi()
stu2.sayHi()
stu3.sayHi()
}
}