object demo6{
//创建伴生类1:
class CustomerService{
def save(){
println(CustomerService.service_name+":over!")
}
}
//创建伴生对象1
object CustomerService{
//私有变量
private val service_name = "CustomerService"
}
//创建伴生类2:
//class Person(private[this] var name:String)//定义在主构造器上,但这种权限下不能执行
class Person(private/*[this]*/ var name:String)//定义在主构造器上
//创建伴生对象2
object Person{
def printperson(P:Person) = println(P.name)
}
def main(args:Array[String]):Unit={
//1对象方法
val customerService = new CustomerService
customerService.save()
//伴生对象伴生类能够互相访问私有成员和方法,但是限制权限则不行
Person.printperson(new Person("xiaobao"))
}
}
输出结果:
CustomerService:over!
xiaobao
当使用如下权限时:
class Person(private[this] var name:String)//定义在主构造器上,但这种权限下不能执行
//class Person(private/*[this]*/ var name:String)//定义在主构造器上
运行结果如下:
(zzjz) [root@VM-16-5-centos scala-learn]# scalac demo6.scala
demo6.scala:19: error: value name is not a member of demo6.Person
def printperson(P:Person) = println(P.name)
^
one error found
使用apply快速创建伴生对象,伴生类:
object demo7{
//创建伴生类
class Person(var name:String = "",var age:Int = 0)
//创建伴生对象
object Person{
//定义apply方法,快速创建伴生对象
def apply(name:String,age:Int)={
new Person(name,age)
}
}
def main(args:Array[String]){
val Xiaobao = Person("xiaobao",21)
println(Xiaobao.name,Xiaobao.age)
}
}
运行结果:
(xiaobao,21)
单例对象的继承:
object demo7{
//创建父类:
class Person{
var name:String = _
def getName() = this.name
}
//创建子类:
class Student extends Person
//创建单例对象继承Person
object Student_object extends Person
def main(args:Array[String]){
//子类调用父类方法
val Xiaobao =new Student
Xiaobao.name = "xiaobaobao"
println(Xiaobao.getName())
//继承父类的单例对象调用父类的方法
Student_object.name = "chuyu"
println(Student_object.getName())
}
}
运行结果:
xiaobaobao
chuyu
方法,变量的重写:
object demo7{
//创建父类:
class Person{
val name:String = ""
def getName() = this.name
}
//创建子类:
class Student extends Person{
//重写字段
override val name:String = "student"
//重写方法
override def getName() = "add_"+super.getName()
}
def main(args:Array[String]){
//子类调用父类方法
val Xiaobao =new Student
println(Xiaobao.name,Xiaobao.getName())
}
}
运行结果:
(student,add_student)