scala的访问权限

20 阅读1分钟

一.Scala的访问权限:

    1. 公共的:不添加修饰符,在任何地方都可以访问
    1. protected:受保护的,在自身和子类中访问
    1. private:私有的,只有在自身中访问,在伴生对象中也可以访问!
    1. private:[this]访问权限,只能被当前对象中使用,在类的内部使用
package level02
 object Class25 {
   object Person {
     def test(p: Person): Unit = {
       // private 在伴生对象中可以访问!
       println(p.password)
       // private[this] 在伴生对象中不能访问的
       // println(p.money)
     }
   }
   class Person() {
     var name: String = "xx"; // 公开的
     protected var birthday: String = "2000-10-10"
     private var password: String = "123456"
     private[this] var money: Int = 100
     def t(): Unit = {
       println(money)
     }
   }
   class Son extends Person() {
     // 2. protected在子类中可访问
     println(birthday)
     // 3. private在子类中不能访问的
     // println(password)
   }
   def main(args: Array[String]): Unit = {
     val p1 = new Person()
     println(p1.name)
     // 2. protected在类的外部无法访问
     // println(p1.birthday)
     new Son()
     // 3. 在伴生对象中访问 类的私有成员
     Person.test(p1)
   }
 }