单例对象

23 阅读1分钟

object 对象名{

属性;

方法;。。。

}

单例对象

只有一个、不能被new

适用于存放工具方法、常量。

 object shew {
    object MyTool {
      // 属性
      val PI = 3.14

      // 方法
      def Area(r: Double): Double = {
        PI * r * r
      }
    }
    def main(args: Array[String]): Unit = {
      // 对象.属性名
      // 对象.方法名()

      println(MyTool.PI)
      println(MyTool.Area(10))
    }
    }

伴生类 和 伴生对象

1. 类和对象同名

2. 在一个文件中

类就是伴生类,对象就是伴生对象。

特点:可以相互访问对方的私有成员

object ccou {
 

  class Student() {
    // private 修饰的属性,无法在类的外部被访问!
    private val hobby = "打游戏"
  }

  object Student {
    def introduce(stu: Student): Unit = {
      println(s"我的爱好是:${stu.hobby}")
    }
  }

  def main(args: Array[String]): Unit = {
    val stu1 = new Student()
    // stu1.hobby // 无法访问私有属性
    Student.introduce(stu1)
  }
}