标签:
在scala中,类和它的伴生对象可以相互访问对方的私有对象
class Person { private var _age = 2 def age_=(num: Int) = this._age = num def age = _age def printObj { println(s"I can see ${Person.obj}") } } object Person { // access the private class field ‘age‘ def double(p: Person) = p._age * 2 private val obj = "Person‘s object" } object Driver extends App { //伴生对象可以引用类的私有变量 val p = new Person println(p.age) p.age = 10 println(Person.double(p)) // prints 20 //类可以引用伴生对象的私有变量 p.printObj //prints I can see Person‘s object }
标签:
原文地址:http://my.oschina.net/cloudcoder/blog/490041