主類:
packagecom.learn.scala.day9
/**
* Created by zhuqing on 2017/2/28.
*/
objectDay9Class {
defmain(args: Array[String]): Unit = {
/**
* 初始化類時木人,可以用括號也可以不用括號
* var person = new Person()
*/
valperson =newPerson
//實際調(diào)用的是 name_=(String)
person.name="Tom"
//實際調(diào)用的是 age_=(Int)
person.age=12
//如果方法沒有參數(shù),可以不寫括號
person incrementAge;
//person.age實際調(diào)用的方法是age()
println("age="+ person.age)
person incrementAgeNoBody;
println("age="+ person.age);
//實際調(diào)用的是方法 call_=(call:String)
person.call ="old man"
println(person.name+" is "+ person.call)
person.setId("11-01")
valrobbie =newPerson
robbie.setId("11-02")
robbie.name="robbie"
//@BeanProperty默認生成的Java式的get冀偶,set方法
robbie.setSchoolName("BeiFang")
println(robbie.getSchoolName)
//標注為@BeanProperty后醒第,默認的get,set方法存在
robbie.schoolName="NanFang"
println(robbie.schoolName)
}
}
學(xué)習(xí)類:
packagecom.learn.scala.day9
importscala.beans.BeanProperty
/**
* Scala的類與Java的類似,scala中默認為公開類
* Created by Robbie on 2017/2/28.
*/
classPerson {
/**
* 屬性默認為公開进鸠,但是必須給默認值稠曼,這點不像Java
* Java類中的屬性一般為私有,讓后提供公開get/set方法客年,但Scala中不提倡這樣中蒲列,
* Scala認為這樣純粹是多寫代碼,浪費時間搀罢。
* Scala默認生成get,set 方法蝗岖,
*? 1.例如age , get方法:age(),set方法age_=(Int),
*? 2.如果屬性是私有的榔至,生成的方法也是私有的抵赢。
* 如果屬性是公有的,生成的方法也是公有的唧取。
*? 3.對val的屬性只會生成get方法
*
*/
varname:String=""
varage: Int =0
//called 是私有的
private varcalled:String="";
/**
* Scala提供了比Java更嚴的訪問限制铅鲤, private[this]表示,只能在當前實例中使用
*/
private[this]varid=""
/**
* //@BeanProperty會自動生成Java規(guī)范的get,set方法
* 標注為@BeanProperty后枫弟,原來默認的get邢享,set方法存在
*/
@BeanPropertyvarschoolName:String=""
/**
* 設(shè)置Id
*
*@param id
*/
defsetId(id:String): Unit = {
this.id= id
}
/**
* called 的get方法
*
*@return
*/
defcall =called
/**
* called的set方法
*
*@return
*/
defcall_=(call:String) = {
if(age<10) {
called="child"
}else if(age<20) {
called="boy"
}else if(age<30) {
called="man"
}else{
called= call
}
}
/**
* 方法默認公開
*/
defincrementAge(): Unit = {
age=age+1
}
/**
* 方法的簡寫可以不帶括號
*/
defincrementAgeNoBody =age=age+1
override defequals(obj: Any): Boolean = {
valother = obj.asInstanceOf[Person]
//other.id 報錯,因為Id是private[this]淡诗,盡管class相同骇塘,但不能在其他實例中使用,
//other.called是可以調(diào)用的
if(!this.called.equals(other.called)) {
false
}else if(!this.name.equals(other.name)) {
false
}else{
true
}
}
}