天天看點

scala-07Scala類的屬性和對象私有字段實戰詳解

第7講:Scala類的屬性和對象私有字段實戰詳解

一、Scala類

//沒有Public,預設是Public級别

Class Person{

  Private var age = 0  //var可改變值的,private級别,與java不同的是這個age必須指派

  Def increment(){age += 1}  

  Def current = age

}

Class Student{

  Var age= 0  

  //聲明一屬性,預設private,與java不同,預設生成age的getter,setter,在scala對應為age的age,age_

}

Object HelloOOP{

  Def main(args:Array[String]:Unit = {

Val person = new Person()

Person.increment()

Println(person.current)

}

二、getter與setter實戰

Val student = new Student

Student.age = 10  

//調用Student類自動生成的Student.setAge,在Scala,是age_ ,來指派

Println(Student.age) 

   //通過Student類自動生成的Student.getAge,在Scala,是age,來取值列印

Class Student{

 private var privateAge = 0

  val name = "Scala"  //自動生成final和getter,也就是隻讀屬性

  def age = privateAge

//限定一個成員隻能歸目前對象所有,為不能歸目前對象的類的方法去使用

}

Object HelloOOP{

Def main(args:Array[String]:Unit = {

Val student = new Student

//Student.name = 10 報錯,隻能讀不能寫

Println(Student.name)

}

三、對象私有屬性實戰

Class Student{

 private[this] var privateAge = 0 

 //類的方法隻能通路自己對象的私有屬性,不能通路其他對象的屬性,也就是目前對象私有

 val name = "Scala"  //自動生成final和getter,也就是隻讀屬性

 def age = privateAge

//方法可以通路這個類的所有私有字段

 def isYonger(other : Student) = privateAge < other.privateAge  

//若privateAge設為對象私有,則報錯,因為other是Student派生的對象,那麼other中也有這個字段,屬于other對象私有,不能被别的對象通路

}