scala-OO-伴生关系

/**
 * Apply
 *
 * object  class
 *
 * object xxx
 * class  xxx
 * 伴生类  和   伴生对象
 * 互为伴生
 **/
object ApplyApp {

  def main(args: Array[String]): Unit = {
//    ApplyTest.static
//
//    for(i <- 1 to 10) {
//      ApplyTest.inc
//    }
//    println(ApplyTest.cnt)

//    val a = new ApplyTest
//    println(a)
//    a.test()

//    val b = ApplyTest()   // 没有使用new   XXX() ==> object apply    经常会用到的  不用new就能实例化
//    println(b)
//    b.test()


    val c = new ApplyTest()  // 对象() ==> class apply  一般是不用
    c()


    val array = Array("PK", "若泽")

  }
}

/**
 * object修饰的东西,调用时不需要new,直接 东西.属性/方法
 */
object Timer {
  var cnt = 0

  def currentCnt = {
    cnt += 1
    cnt
  }
}

class ApplyTest {
  println(" ApplyTest class enter... ")

  def test(): Unit = {
    println("ApplyTest class test method invoked...")
  }

  def apply()  = {
    println("ApplyTest class apply method invoked...")
  }

  println(" ApplyTest class leave... ")
}


object ApplyTest {
  println(" ApplyTest object enter... ")

  var cnt = 0

  def inc = cnt += 1  // 这只是方法的定义,此处到现在为止还没被调用

  def static = {
    println(" i am a static method...")
  }

  def apply()  = {
    println("ApplyTest object apply method invoked...")
    new ApplyTest
  }

  println(" ApplyTest object leave... ")
}

输出结果:

 ApplyTest class enter... 
 ApplyTest class leave... 
ApplyTest class apply method invoked...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值