伴生类和伴生对象

65 阅读1分钟

当同名的类和单例对象在同一个源码文件时,这个类称为单例对象的伴生类,对象称为类的伴生对象。

要求:

1. 类名和对象名必须同名。

2. 必须在同一个源码文件中。

package level02

object class02 {
  /*
   * 伴生类 和 伴生对象
   * 1. 类和对象的名字是一样的
   * 2. 他们在同一个文件中
   * 特点:可以访问对方的私有(private)属性
   */

  class Student() {
    // private 修饰的属性,在类的外部(在当前的class之外)无法访问!
    private val name: String = "小花"
  }

  object Student {
    def sayHello(stu: Student): Unit = {
      // 在伴生对象中,访问伴生类的私有属性!
      println(s"${stu.name}")
    }
  }

  def main(args: Array[String]): Unit = {
    val stu1 = new Student()
    // stu1.name 是错误的,无法访问
    Student.sayHello(stu1)
  }
}

image.png

一个类只能产生一个对象

package level02

object class03 {
  /*
   * 伴生类 和 伴生对象 实现 单例模式: 一个类只能产生一个对象!
   * */

  // 1. 让构造函数变成私有的。 在类的外部,就无能通过new来创建对象了
  class Student private () {
    // private 修饰的属性,在类的外部(在当前的class之外)无法访问!
    private val name: String = "小花"
  }

  object Student {
    val instance = new Student() // 在伴生对象中,可以访问伴生类的私有成员
    def getInstance: Student = {
      instance
    }
  }

  def main(args: Array[String]): Unit = {
    // val stu1 = new Student()
    // val stu2 = new Student()
    // val stu3 = new Student()
    // val stu4 = new Student()
    val stu1 = Student.getInstance
    val stu2 = Student.getInstance

    println(stu1 == stu2) // true
  }
}

image.png