class ApplyDemo(var name:String){
def apply() = "apply in class"
def test{
println("test"+name)
}
}
/**
* 伴生对象,相当于类的静态方法
*/
object ApplyDemo {
private var n ="tst"
def stat{
println("static method"+n)
}
def apply(name:String) = new ApplyDemo(name)
def apply() = new ApplyDemo(n)
var count = 0
def incc = {
count += 1
}
}
object Study1 {
def main(args:Array[String]) {
ApplyDemo.stat
//类名后面加括号,相当于调用伴生对象的apply方法
val a = ApplyDemo()
a.test
val c = ApplyDemo("ccc")
c.test
//对象加括号相当于调用对象的apply方法
println(a())
val b = ApplyDemo.apply()
b.test
println(a.apply())
for(i <- 0 until 10){
ApplyDemo.incc
}
println(ApplyDemo.count)
}
}
scala 伴生类 伴生对象 apply
最新推荐文章于 2024-09-24 17:58:12 发布