scala中的访问权限

2 阅读1分钟

访问权限:类的成员(属性,方法)在哪些地方可以被访问?

  1. private : 私有的

(1)在类的内部可以访问

(2)在类的外部不能访问

(3)在伴生对象中可以访问 */

case object class15 {
 class Student(var name:String,private var age:Int) {
   def say():Unit = {
     println(s"${this.age}") // (1) 在类的内部可以访问。
   }
 }

 object Student {
   def test(student: Student): Unit = {
     println(student.age) // (3) 在伴生对象中可以访问。
   }
 }

 def main(args: Array[String]): Unit = {
   val s1 = new Student("小花", 18)
   s1.say()
   // println(s1.age) // 报错。(2) 在类的外部不能访问。
   Student.test(s1)

2. protected : 受保护的

(1)在类的内部可以访问

(2)在类的外部不能访问

(3)在伴生对象中可以访问

(4)在子类中可以访问,与之对应的是:private修饰的,在子类中无法访问

case object class16 {
 class Student(var name:String,private var age:Int, protected var weight:Int) {
   def say():Unit = {
     println(s"${this.age}, ${this.weight}") // (1) 在类的内部可以访问。
   }
   
 }

 object Student {
   def test(student: Student): Unit = {
     println(student.weight) // (3) 在伴生对象中可以访问。
   }
 }

 class Major(name:String, age:Int, weight:Int) extends Student(name, age, weight) {
   // 在子类中通过super来访问父类
  // println(super.age) // 报错 (4) private修饰的,在子类中无法访问。
   println(weight) // 正常 (4) protected修饰的,在子类中可以访问。
 }

 def main(args: Array[String]): Unit = {
   val s1 = new Student("小花", 18, 100)
   s1.say()
   // println(s1.weight) // 报错 (2) 在类的外部不能访问。
   Student.test(s1)
 }

2.private [this] :

更加严格的私有保护,这个属性(方法)只能在调用他的同一个实例内实现

(1)在类的内部可以访问

(2)在类的外部不能访问

(3)在伴生对象中可以访问

(4)在子类中可以访问,与之对应的是:private修饰的,在子类中无法访问

case object class17 {
 class Student(var name:String,private var age:Int, protected var weight:Int) {
   private[this] var pwd = 123 // 密码
 }

 object Student {
   def test(student: Student): Unit = {
     println(student.age) // 普通的private在伴生对象中可以访问
     // println(student.pwd) // 报错 (3) 在伴生对象中,不能访问private[this]
   }
 }