复习

28 阅读1分钟

1.辅助构造函数

//1.主构造函数 class Student()

//辅助构造函数 提供更多的方式来创建对象
class Student(var name:String, val age:Int) {

  //辅助构造函数
  //特点:1.名字就是this    2.第一句代码就是调用主构造器
  def this() = {
    this("未知的",18)   //调用主构造器
  }

  def this(age:Int) = {
    this("未知的",age)
  }

  def sayHi(): Unit = {
    println(s"我是${name}, 我今年${age}")
  }
}

object Class01 {
  def main(args: Array[String]): Unit = {
    //创建对象   new 会自动调用构造函数
    val stu1 = new Student("小花", 18)
    val stu2 = new Student()
    val stu3 = new Student(20)


    //调用对象的方法
    stu1.sayHi()

    //调用对象的方法
    stu2.sayHi()
    stu3.sayHi()

    //修改对象的属性

    stu1.name = "小花花"
    stu1.sayHi()
  }
}