Scala中的访问权限

27 阅读1分钟

访问权限

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

1.private :私有的 (1)在类的内部可以访问。

(2)在类的外部和子类中都不能访问。

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

protected:受保护的。

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

private[this]:更加严格的私有权限。这个属性(方法)只能在调用它的同一个实例使用

代码展示:

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

  protected def sayWeight():Unit = { println(weight)}
}
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 来访问父类:只能调用方法,不能调用属性
//sayAge() //  报错,(4)private修饰的,在子类中无法访问
  // sayWeight()正常,protected修饰的,在子类中可以访问

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

}