scala的访问权限

30 阅读1分钟

访问权限控制

1.默认访问权限

2.使用 protected(被保护的) 修饰符

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

(2)在子类中,通过super 来访问protected 修饰的成员

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

    protected var gender:String = "女"

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

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


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

3.private(私有的)

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

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

eg1:

object class20 {
  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)
  }
}

eg2:

object class20 {
  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()
    stu.test()
    //private成员,不能在类的外部,通过对象,属性的方法来访问
    //报错:stu.age
    Student.test(stu)
  }
}