object Tools { /* *伴生类 和 伴生对象
- 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
} }