scala中的类和对象

22 阅读1分钟

// 类是属性的集合

// Student,构造函数用来创建对象的

// 辅助构造函数,提供多种创建对象的方式

// 类是属性的集合
// Student,构造函数用来创建对象的
//         辅助构造函数,提供多种创建对象的方式
class Student(var name:String, var age:Int) {
  println("构造函数被调用...")

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

  // 辅助构造函数
  // (1)它的名字就是this
  // (2)它内部的第一句代码必须是调用 主构造函数 this("无名氏", 0)
  def this() = {
    this("无名氏", 0)
    println("辅助构造函数1被调用...")
  }

  def this(name: String) = {
    this(name, 0)
    println("辅助构造函数2被调用...")
  }
}

    def main(args: Array[String]): Unit = {
      // 创建一个学生对象
      // val stu1 = new Student("小花", 18)
      // 调用对象的方法
      // stu1.sayHi()

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

      // 这里没有设置参数,它会调用辅助构造函数
      // val stu2 = new Student()
      // stu2.sayHi()

      // 这里设置了一个参数,它会调用辅助构造函数
      val stu3 = new Student("小明")
      stu3.sayHi()
}
// 私有 private
class Student(var name:String, var age:Int) {

  // 在方法前面添加 private,那这个方法是私有的,它不能在 class 的外部被访问
  private def song(): Unit = {
    println("我在唱歌....")
  }

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

    // 私有方法,在类的内部是可以正常调用的
    song()
  }
}

def main(args: Array[String]): Unit = {
  val stu3 = new Student("小明",18)
  stu3.sayHi()
  // stu3.song() // 会报错
}