scala 访问权限(2

53 阅读1分钟
/*
 *访问权限控制
 *
 * 1.默认访问权限
 * 2.使用protected(被保护的)修饰符
 *  (1)在类的外部 不能直接通过对象 属性的方式来访问
 *  (2)在子类中 通过super来访问protected的方法
 * 3.private 私有的
 *  (1)在子类中 无法访问
 *   (2)在伴生对象 伴生类中可以访问
 * 4.private[this]私有 只能在当前类中访问
 *    子类无法访问 伴生对象 伴生类中不可以访问
 * */


object class11243 {
  class Student() {

    private var age:Int = 10

    private [this] var secret:String = "xx日 xx事"

    def test():Unit = {
      //if() {}
      println(secret)
    }
  }

  object Student {
    def test(stu: Student):Unit = {
      //在伴生对象中 可以通过对象 属性的方法来访问
      println(stu.age)
      //private[this]私有 只能在当前类中访问
      //println(stu.secret)
    }
  }

  def main(args: Array[String]): Unit = {
    val stu = new Student()
    //private 成员 不能在类的外部 通过对象 属性的方法来访问
    //报错:stu:.age
    Student.test(stu)
  }
}