单例对象(只有一个的对象)

image.png

  1. object Person{
  2. private var lastId = 0
  3. def newpersonId() = {
  4. lastId +=1
  5. lastId
  6. }
  7. }
  8. printf("this frist person id is %d.\n",Person.newpersonId())
  9. printf("this frist person id is %d.\n",Person.newpersonId())
  10. printf("this frist person id is %d.\n",Person.newpersonId())

image.png
静态字段,每次调用用到的都是同一个对象的值

伴生对象

image.png
需要满足相同名字

  1. class Person{ //这个玩意叫伴生类,两者的名字是一样的
  2. private val id = Person.newPersonId() //调用了伴生对象中方法,相当于是同一个属性(静态方法)
  3. private var name =""
  4. def this(name : String){
  5. this()
  6. this.name = name
  7. }
  8. def info(){printf("this id of %s is %d.\n"name,id)}
  9. }
  10. object Person{
  11. private var lastId = 0
  12. private def newpersonId() = {
  13. lastId +=1
  14. lastId
  15. }
  16. def main(args:Array[String]){
  17. val person1 = new Person("Ziyu")
  18. val person2 = new Person("Minxing")
  19. person1.info()
  20. person2.info()
  21. }
  22. }

image.png
验证两者合二为一

  1. class Person{ //这个玩意叫伴生类,两者的名字是一样的
  2. private val id = Person.newPersonId() //调用了伴生对象中方法,相当于是同一个属性(静态方法)
  3. private var name =""
  4. def this(name : String){
  5. this()
  6. this.name = name
  7. }
  8. def info(){printf("this id of %s is %d.\n"name,id)}
  9. }
  10. object Person{
  11. private var lastId = 0
  12. def newpersonId() = { //这里去掉了private
  13. lastId +=1
  14. lastId
  15. }
  16. def main(args:Array[String]){
  17. val person1 = new Person("Ziyu")
  18. val person2 = new Person("Minxing")
  19. person1.info()
  20. person2.info()
  21. }
  22. }

去掉private之前,使用javap进行反编译,这里看不到对应的方法
image.png
去掉之后
image.png
去掉之后就可以看到。两者合二为一了

应用程序对象

image.png
运行(没有class可以直接运行),有class要先用scalac先编译
image.pngimage.png
image.png

apply和update方法

apply

相当于()
image.png
image.png
image.png
image.png
image.png

伴生类和伴生对象的apply运用
image.png
image.png
image.png
总之,就是有实例化对象的调用,才会使用到伴生类中的方法,其余的都是在伴生对象中的方法
image.png
这个也是先调用伴生对象中的额方法

update方法

image.png
image.png