一,伴生类和伴生对象
定义:当同名的类和单例对象在同一个源码文件时,这个类称为单例对象的伴生类,对象称为类的伴生对象。
package level02
object day51 {
/*
*
* 伴生类 和 伴生对象
* 1,类和对象的名字是一样的
* 2,他们在同一个文件中
*
* 特点:可以访问对方的私有(private)属性
*/
class Student() {
// privat 修饰的属性,在类的外部(在当前的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)
}
}
重点代码:
1,一个类只能产生一个对象
什么是单例模式?👇
就是通过技术手段,让某个类只能有一个对象实例。这样做的好处就节约资源,能更加精准地管理。
object day52 {
/*
*
* 伴生类 和 伴生对象 实现 单列模式:一个类只能产生一个对象1
*
*/
//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 = Student.getInstance
val stu2 = Student.getInstance
println(stu1 == stu2) // true
}
}