可见性修饰符
本课属于 Coddy Kotlin 学习旅程的“面向对象编程”单元。第 8 课,共 57 课。
封装表示类控制其数据的使用方式。可见性修饰符决定谁能看到成员。private 会将成员隐藏起来,使其无法被类之外的任何内容访问,因此只能通过类自己的方法访问:
class Account {
private var balance = 0
fun deposit(amount: Int) {
if (amount > 0) balance += amount
}
fun report() = "balance: $balance"
}在 main 中:
val a = Account()
a.deposit(50)
a.deposit(-999)
println(a.report())
// a.balance = 1_000_000 // 错误:无法访问 'balance',它是私有的输出:
balance: 50Kotlin 有四种修饰符。如果没有指定修饰符,声明默认为 public,在任何地方都可见:
public // 默认:在任何地方都可见
internal // 在同一模块(app 或库)中可见
protected // 在类及其子类中可见
private // 在类内部可见(顶层声明则在文件内部可见)私有辅助函数可以让公共接口保持精简。调用者只需了解这个类的功能,无需了解实现方式:
class Password(private val text: String) {
val isStrong: Boolean
get() = hasDigit() && text.length >= 8
private fun hasDigit() = text.any { it.isDigit() }
}在 main 中:
println(Password("secret123").isStrong)
println(Password("short1").isStrong)输出:
true
false构造函数属性也可以使用修饰符:private val 用于存储一个外部代码无法读取的值。隐藏数据可以让类检查每次更改,并确保遵守规则:
class Locker(private val code: String) {
private val items = mutableListOf<String>()
fun store(item: String, code: String): Boolean {
if (code != this.code) return false
items.add(item)
return true
}
}挑战
简单完成类 Locker(private val code: String)。它的 items 列表是私有的。只有代码匹配时,store(item, code) 才会添加项目,并返回是否添加成功;代码匹配时,open(code) 会返回用 , 连接的项目(如果列表为空则返回 empty),否则返回 wrong code。
提供的代码会读取储物柜的代码,然后读取 put <code> <item> 或 open <code> 命令。每条 put 命令都会输出 stored 或 denied,每条 open 命令都会输出对应结果。
你的代码写在 Locker.kt 中。Main.kt 包含提供的输入/输出代码,不能编辑。
亲手试试
fun main() {
// 提供的输入输出代码:保持原样。
val input = generateSequence(::readLine).toList()
val locker = Locker(input[0])
for (cmd in input.drop(1)) {
val p = cmd.split(" ")
if (p[0] == "put") println(if (locker.store(p[2], p[1])) "stored" else "denied")
else println(locker.open(p[1]))
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
自己练习: Kotlin 在线编辑器