scala中的对象私有字段

来源:互联网 发布:电脑淘宝扫一扫在哪 编辑:程序博客网 时间:2024/05/17 14:27

在scala中方法可以访问,方法可以访问该类的所有对象的私有字段,

class Person{  private var age = 0  def increment(){age += 1}  //可以访问另一个对象的私有字段  def younger(other : Person)= { age < other.age }}

因为other同样是Person的对象, 所以可以访问other.age

scala中提供更严格的访问限制,通过private[this]来实现

class Person{  private[this]var age = 0  def increment(){age += 1}  //类似于其他对象.age这样的访问将不被允许  def younger(other : Person)= { age < other.age }}

0 0
原创粉丝点击