1>单例对象
scala中可以用object来达到静态方法或静态字段
例如:
//如下的变量和方法都是静态的
//object里面的内容只有第一次使用的时候才会执行
object University{
private var studentNo = 0
def newStudentNo = {
studentNo += 1
//最后一行代表返回值
studentNo
}
}
2>伴生对象
1.在scala中通过类和类同名的”伴生”对象达到既有实现方法,又有静态方法的类
2.伴生类可以访问他的伴生对象可以所有的成员(包括private成员),但必须存在于同一个源文件中
3.object并不在class作用区域内,例如University类中的必须要
4.University.newStudentNo才可以访问newStudentNo()方法
class University{
val id = University.newStudentNo
private var number = 0
def aClass(number:Int){
this.number += number
}
}
//伴生对象
object University{
……….}
3>apply方法
例如:
apply分为两种方式:object和class中的用法
apply优点:
class ApplyTest{
def apply() = println(“I am class ApplyTest”)
def account{
println("class ApplyTest account")
}
}
//object中的apply方法可以创建ApplyTest,返回ApplyTest对象
object ApplyTest{
def apply() = {
println("I am object ApplyTest")
new ApplyTest
}
}
object ApplyOperation {
def main(args:Array[String]){
//也是调用了apply方法
val array = Array(1,2,3,4,5)
//所以并没有new关键字
val a = ApplyTest()
a.account
// val a = new ApplyTest
// a.account
// a()就可以调用class中的apply方法
// println(a())
}
}