25 scala的访问权限(2)

30 阅读2分钟

(三)protected访问权限

protected : 受保护的。它的特点有如下4个:

(1) 在类的内部可以访问。

(2) 在类的外部不能访问。

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

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


object class16 {

  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() //  正常 (4) protected修饰的,在子类中可以访问。

  }

  def main(args: Array[String]): Unit = {

    val s1 = new Student("小花", 18, 100)

    s1.say()

    // println(s1.weight) // 报错。 (2)在类的外部不能访问。

    Student.test(s1)

  }

}

(四)private[this]控制方法作用域

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

它的特点如下:

       (1) 在类的内部可以访问。

       (2) 在类的外部不能访问 private[this]。

       (3) 在伴生对象不能访问 private[this]。

       (4) 在子类中不能访问 private[this]。


object class17 {

  class Student(var name:String,private var age:Int, protected var weight:Int) {

    private[this] var pwd = 123 // 密码

  }

  

  object Student {

    def test(student: Student): Unit = {

      println(student.age)     // 普通的private在伴生对象中可以访问

      // println(student.pwd)  报错  (3) 在伴生对象中,不能访问private[this]

    }

  }

  def main(args: Array[String]): Unit = {

    val s1 = new Student("小花", 18, 100)

    Student.test(s1)

 

  }

}

更加严格的私有权限,表示该字段或方法只能在调用它的同一个实例内部可见。这意味着即使在同一类的其他实例中,也无法访问该字段或方法。不能在伴生对象中访问,不能在函数参数中访问。

 

(五)案例

银行账户存钱取钱的例子。要求实现账户类,它有一个私有属性:余额。还有三个方法。具体如下:

  • balance 余额

  • deposit() 存钱

  • withdraw() 取钱

  • transfer(to: 账户, amount:Dobule) 转账。是调用to对象的方法来增加余额,而不是直接操作balance属性!


class BankAccount(private var balance: Double) {  
  def deposit(amount: Double): Unit = {if (amount > 0) balance += amount}  
  def getBalance: Double = balance  
  def transfer(to: BankAccount, amount: Double): Unit = {  
    if (amount > 0 && this.balance >= amount) {  
      this.balance -= amount  
      to.deposit(amount)  // 通过方法调用转账    
    }  
  }  
  
  def clear(o:BankAccount): Unit = {  
    o.balance = 0 // private[this] 会报错  
  }  
}  
  
object Test {  
  def main(args: Array[String]): Unit = {  
    val account1 = new BankAccount(1000)  
    val account2 = new BankAccount(500)  
    account1.transfer(account2, 200)  
//    account1.clear(account2)  
    println(s"Account 1 Balance: ${account1.getBalance}")  // 800    
    println(s"Account 2 Balance: ${account2.getBalance}")  // 700    
  }  
}