第五章 类
getter和setter
object HelloWorld {
def main(args: Array[String]) {
val p = new Person
p.age = 10
p.age = 5
print(p.age) // 10
}
}
class Person{
private var privateAge = 0
def age = privateAge // 相当于java的setter
def age_=(newValue: Int) = { // 相当于java的getter
if(newValue > privateAge) privateAge = newValue
}
}