/**
* 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...