4.4 Scala伴生对象伴生类

Class和object名称相同,object就是class的伴生对象,class就是object的伴生类

Scala中没有static

Scala没有Java中的static 静态成员
替代品是 Scala中有:单例对象:Singleton object

除了用Object替换Class之外,单例对象定义看上去就像是类的定义,如下例子

object ObjectApp {
  def main(args: Array[String]): Unit = {
    print(Timer.currentCnt())
    print(Timer.currentCnt())
    print(Timer.currentCnt())
  }

}

object Timer{
  var cnt = 0;

  def currentCnt():Int = {
    cnt += 1
    cnt
  }
}

在这里插入图片描述

object Timer{
  var cnt = 0;

  def currentCnt():Int = {
    cnt += 1
    cnt
  }
}

class Timer{

  var cnt = 0;

  def currentCnt():Int = {
    cnt += 1
    cnt
  }
}

在这里插入图片描述
Object 类似是一个全局的

伴生对象为Timer 同名伴生类为Timer

单例对象会在第一次被访问的时候初始化。

Apply

object ObjectApp {
  def main(args: Array[String]): Unit = {
//    print(new Timer().currentCnt())
//    print(new Timer().currentCnt())
//    print(new Timer().currentCnt())
    val test = new ApplyTest
    println(test)
    println(test.test())
  }

}


object ApplyTest{
  var cnt = 0

  def inc={
    cnt += 1
  }

  def test() = {
    print("-------------Object test------------------")
  }

  print("---------------ApplyTest object leave------------")
}

class ApplyTest{
  def test() = {
    print("--------------ApplyTest class-------------------")
  }
}

new 出来 走的是class

在这里插入图片描述

val b = ApplyTest() //名字() —> object.apply

    val b = ApplyTest()  //名字()  ---> object.apply
    println(b)
    b.test()
object ApplyTest{
  println("---------------ApplyTest object enter------------")
  var cnt = 0

  def apply() = {

    println("--------------- object apply------------")
    new ApplyTest //在object里面的apply方法里 去new一个对应的class
  }

在这里插入图片描述

val c = new ApplyTest()

new class 出来 不会调用class里面的方法


class ApplyTest{
  def test() = {
    println("--------------ApplyTest class-------------------")
  }


  def apply() = {

    "--------------- object apply------------"
  }
}

在这里插入图片描述

println(c())

当打印C() 时就会走Class里面的apply方法
在这里插入图片描述

总结

Object Class 同名 伴生类 伴生对象

//***********************************************************
名字() -------> object apply  // 一般情况下 在这个apply方法里面是new一个伴生类
对象() -------> class apply   // 一般不用
//***********************************************************

应用

    new Array[Int](4)
    Array(1,2,3,4)

直接Array就会调用 apply方法

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oifengo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值