访问控制与方法重写

17 阅读1分钟

private

默认情况下,类的属性在可以通过对象.属性名的方式来获取,如果不希望在类的外部被访问,可以用private来修饰。

格式

class 类名{

private 属性

private 方法

}

编码示例

class Student(){
  private val name:String;
}

object Test{
  def main(args: Array[String]): Unit = {
    val s = new Stuent()  
s.name // 错误~~~~
  }
}

案例:

object base48 {
  //私有 private
  class Student(var name:String,var age:Int) {
    //在方法前面添加private,那这个方法是私有的,它不能在class的外部被访问
    private def song():Unit = {
      println("我在唱歌...")
    }

    def sayHi(): Unit = {
      println(s"我是${name},我今年${age}岁")
    }

    //私有方法,在类的内部是可以正常调用的
    song()
  }

  def main(args: Array[String]): Unit = {
    val stu3 = new Student("小敏",18)
    stu3.sayHi()
    //stu3,song()   //报错
  }
}