30 阅读1分钟
/*
  访问权限:类的成员 (属性,方法) 在哪些地方可以被访问.
  1.private : 私有的.
  (1) 在类的内部可以访问
  (2) 在类的外部都不能访问
  (3) 在伴生对象中可以访问
 */

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

  class Major(name:String, age:Int, height:Int) extends Student(name,age,height){
    this.age
    super.
  }

  def main(args: Array[String]): Unit = {
    val s1 = new Student("小花",18)
    s1.say()
    // println(s1.age) //  报错.   (2)
class Student(var name:String,private var age:Int,protected var weight:Int) {
  def say(): Unit = {
    println(s"s${this.age},${weight}") // (1) 在类的内部可以访问
  }

  private def sayAge(): Unit = {
    println(age)
  }

  protected def sayWeight(): Unit = {
    println(weight)
  }
  
  object Student {...}
  
class Major(name:String, age:Int, height:Int) extends Student(name,age,height){
  // 在子类中通过 super来访问父类: 只能调用方法,不能直接调研属性
  
  // sayAge()//  报错 (4) private修饰的,在子类中无法访问。
  sayWeight() // 正常 (4)prtected修饰的,在子类中可以访问