在scala中,类和它的伴生对象可以相互访问对方的私有对象
classPerson{privatevar_age =2defage_=(num:Int) =this._age = numdefage = _agedefprintObj{ println(s"I can see${Person.obj}") }}objectPerson{// access the private class field 'age'defdouble(p:Person) = p._age *2privatevalobj ="Person's object"}objectDriver extends App{//伴生对象可以引用类的私有变量valp =newPersonprintln(p.age) p.age =10println(Person.double(p))// prints 20//类可以引用伴生对象的私有变量p.printObj//prints I can see Person's object}
网友评论