伴生类和伴生对象应在同一个文件中,名字相同;
class类称为object的伴生类,object称为class的伴生对象
实例1:
class Person(uname: String,Uage: Int) {
println("class 进入到Person的class类中")
var name: String = uname
var age: Int = age
private var address: String = "亚洲"
def this() { //从构造方法
this("xxx",0)
println("class this() 从构造方法")
}
def this(age: Int) {
this("xxx",age)
}
def this(name: String) {
this(name,0)
}
println("class变量定义完成,准备定义方法)
def printMsg(): Unit = {
println(Person.name + " " + Person.age + " " + address)
Person.showMsg()
}
println("class 类一次游,准备离开Person类")
}
object Person { //伴生对象 Static
println("object进入到Person伴生对象中...")
private val name: String = "中国"
private val age: Int = 71
def apply(uname: String,uage: Int): Person(uname,uage)
def apply(uname: String): Person = new Person(uname)
def apply(uage: Int): Person = new Person(uage)
def apply(): Person = new Person()
println("object 变量定义完成,准备定义方法")
def showMsg(): Unit = {
println(Person.name + " " + Person.age)
}
def showBSClass(p:Person): Unit = {
println("object main 进入main方法中")
val po1 = Person("Suna",17)
val po2 = Person()
val po3 = Person("NanJing")
val po4 = Person(17)
Person.showBSClass(po1)
val person = Person.apply("xz",16)
//创建多个对象,程序会先运行完第一个,再运行下一个
var personNew: Person = new Person("Aythna",17)
var PersonNew2: Person = new Person("Kirito",17)
var p1 = new Person()
var p2 = new Person(21)
var p3 = new Person("Aythna")
var personobj = Person
personobj.showMsg()
personNew.printMsg()
//personobj.printMsg() //无法访问,是错误的
}
println("object 伴生对象一次游结束")
}
实例2:
class Student(uname: String,uage: Int) { //伴生类
private val name: String = uname
private val age: Int = age
def this(age: Int) {
this("Aythna",age)
}
def printMsg(): Unit = {
println(Student.name + "," + Student.age + "岁")
Student.showMsg()
}
}
object Student {
private val name = "Aythna"
private val age = 17
def apply(uname: String,uage: Int): Student = new Student(uname,uage)
def showMsg(): Unit = {
println(Student.name + " " + Student.age)
}
def main(args: Array[String]): Unit = {
val s1: Student = new Student("Kirito",16)
s1.printMsg()
}
}