Scala 作为一门融合了面向对象与函数式编程的语言,其访问权限系统相比 Java 更加灵活和精细。本文将从基础的private、protected到高级的private[this],结合实例深入解析 Scala 的访问权限控制机制。
一、Scala 访问权限基础
Scala 提供了三种基础访问修饰符:
- 无修饰符:默认权限,等同于 Java 的
public - private:私有访问
- protected:受保护访问
1. protected 访问权限
protected修饰的成员具有以下特性:
package level02
/*
访问权限: 类的成员(属性,方法)在哪些地方可以被访问。
1. protected : 受保护的。
(1) 在类的内部可以访问。
(2) 在类的外部不能访问。
(3) 在伴生对象中可以访问。
(4) 在子类中可以访问;与之对应的是:private修饰的:在子类中无法访问
*/
object Class20 {
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()//报错
sayweight()
}
def main(args: Array[String]): Unit = {
val s1 = new Student("小红", 18, 100)
s1.say()
// println(s1.weight) // 报错:(2) 在类的外部不能访问。
Student.test(s1)
}
}
二、精细化控制:private [this]
Scala 提供了更严格的私有访问控制 ——private[this](对象私有)。
package level02
/*
访问权限: 类的成员(属性,方法)在哪些地方可以被访问。
1.private[this]:更加严格的私有保障。这个属性(方法)只能在调用它的一个实例内使用
(1) 在类的内部可以访问。
(2) 在类的外部不能访问。 private [this]
(3) 在伴生对象中不能访问。 private [this]
(4) 在子类中不能访问 private [this]
*/
object Class21 {
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)
// println(student.pwd)
}
}
def main(args: Array[String]): Unit = {
val s1 = new Student("小花",18,100)
Student.test(s1)
}
}
三、实战案例:银行账户系统
让我们通过一个银行账户的例子,看看如何合理运用访问权限控制:
package level02
/*
模拟银行账号
余额
存钱
取钱
转账
*/
object class22 {
class Bank(private[this] var balance:Double) {
// 存
def deposit(amount:Double):Unit = {
balance += amount
}
// 取
def withdraw(amount:Double):Unit = {
if(balance >= amount) {
balance -= amount
}
}
def getBalance():Double = balance
}
object Bank {
def clear(bank: Bank): Unit = {
bank.balance = 0
}
}
def main(args: Array[String]): Unit = {
val bank = new Bank(100)
bank.deposit(1000)
bank.withdraw(200)
// bank.balance -= 100
// bank.balance -= 100
Bank.clear(bank)
println(bank.getBalance())
}
}
四、访问权限选择指南
| 修饰符 | 访问范围 | 适用场景 |
|---|---|---|
| 默认 | 任何地方 | 对外提供的 API |
| private | 类内部、伴生对象 | 需要内部协作的实现细节 |
| private[this] | 当前对象实例 | 实例独有的敏感数据 |
| protected | 类内部、伴生对象、子类 | 子类需要继承的实现细节 |
| private [包名] | 指定包内 | 包内组件间的协作 |
总结
Scala 的访问权限系统提供了丰富而精细的控制能力:
- 基础权限:
private和protected满足大多数场景需求 - 对象私有:
private[this]提供最严格的实例级保护 - 包级权限:
private[包名]支持模块化设计 - 伴生对象:共享私有成员,实现工厂模式和工具方法