单例对象(只有一个的对象)
object Person{
private var lastId = 0
def newpersonId() = {
lastId +=1
lastId
}
}
printf("this frist person id is %d.\n",Person.newpersonId())
printf("this frist person id is %d.\n",Person.newpersonId())
printf("this frist person id is %d.\n",Person.newpersonId())
静态字段,每次调用用到的都是同一个对象的值
伴生对象
需要满足相同名字
class Person{ //这个玩意叫伴生类,两者的名字是一样的
private val id = Person.newPersonId() //调用了伴生对象中方法,相当于是同一个属性(静态方法)
private var name =""
def this(name : String){
this()
this.name = name
}
def info(){printf("this id of %s is %d.\n"name,id)}
}
object Person{
private var lastId = 0
private def newpersonId() = {
lastId +=1
lastId
}
def main(args:Array[String]){
val person1 = new Person("Ziyu")
val person2 = new Person("Minxing")
person1.info()
person2.info()
}
}
验证两者合二为一
class Person{ //这个玩意叫伴生类,两者的名字是一样的
private val id = Person.newPersonId() //调用了伴生对象中方法,相当于是同一个属性(静态方法)
private var name =""
def this(name : String){
this()
this.name = name
}
def info(){printf("this id of %s is %d.\n"name,id)}
}
object Person{
private var lastId = 0
def newpersonId() = { //这里去掉了private
lastId +=1
lastId
}
def main(args:Array[String]){
val person1 = new Person("Ziyu")
val person2 = new Person("Minxing")
person1.info()
person2.info()
}
}
去掉private之前,使用javap进行反编译,这里看不到对应的方法
去掉之后
去掉之后就可以看到。两者合二为一了
应用程序对象
运行(没有class可以直接运行),有class要先用scalac先编译
apply和update方法
apply
相当于()
伴生类和伴生对象的apply运用
总之,就是有实例化对象的调用,才会使用到伴生类中的方法,其余的都是在伴生对象中的方法
这个也是先调用伴生对象中的额方法