Scala的访问权限

43 阅读3分钟

Scala的访问权限概述

Scala中的属性、方法可以通过访问控制符来设置不同的访问权限。不同的访问控制符可以决定是否可以被外部类访问。

有四种访问控制权限,分别为:

1.默认访问权限。

Scala中的默认访问权限相当于Java中的public,Scala中如果一个变量没有任何修饰符,就代表默认访问权限。作用域:全部

2.protected 访问权限。

作用域:本类,子类

(1)在类的外部,不能直接通过对象.属性的方式来访问

(2)在子类中,可以访问protected 修饰的成员

/*
*
*  访问权限控制
*
*  1. 默认访问权限
*  2. 使用protected ( 被保护的 ) 修饰符
*       (1)在类的外部,不能直接通过对象.属性的方式来访问
*       (2)在子类中,可以访问protected 修饰的成员
* */

object class01 {

  // name 属性具有默认的访问权限
  class Student(var name:String, protected var gender:String) {

  }

  def main(args: Array[String]): Unit = {
    val s1 = new Student("小花","女")
    // 类的外部可以访问
    println(s1.name)
    // protected属性,在类的外部无法访问
    // println(s1.gender)
  }
}

3.private 访问权限。

作用域:类内部(伴生对象:定义方法传入类的对象)

(1)在子类中,无法访问。

/*
*
*  访问权限控制
*
*  1. 默认访问权限
*  2. 使用protected ( 被保护的 ) 修饰符
*       (1)在类的外部,不能直接通过对象.属性的方式来访问
*       (2)在子类中,可以访问protected 修饰的成员
*  3. private(私有的)
*       (1)在子类中,无法访问。
* */

object class02 {

  // name 属性具有默认的访问权限
  class Father() {
    val name:String = "小花"

    protected var gender:String = "女"

    protected def test(): Unit = {
      println("test")
    }

    private val age:String = "18"
    private def test1(): Unit = {
      println("test1")
    }

  }

  // 在子类中,我们通过super 来访问父类
  class Son extends Father{
    //  修饰的成员,可以在子类中,访问
    super.test()
    println(gender)
    //  private 修饰的成员,可以在子类中,不访问
    // super.test1()
    // println(age)
  }

  def main(args: Array[String]): Unit = {
    var son1 = new Son()
  }
}

(2)在伴生对象,伴生类中可以访问

/*
*
*  访问权限控制
*
*  1. 默认访问权限
*  2. 使用protected ( 被保护的 ) 修饰符
*       (1)在类的外部,不能直接通过对象.属性的方式来访问
*       (2)在子类中,可以访问protected 修饰的成员
*  3. private(私有的)
*       (1)在子类中,无法访问。
*       (2)在伴生对象,伴生类中可以访问。
* */

object class03 {
  class Student() {

    private var age:Int = 10

  }

  object Student {
    def test(student: Student): Unit = {
      // 在伴生对象中,可以通过对象.属性的方法来访问
      println(student.age)
    }
  }

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

4.private[this]访问权限。

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

object class03 {
  class Student() {

    private var age:Int = 10

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

    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)
  }
}