初学伴生类和伴生对象

伴生类和伴生对象应在同一个文件中,名字相同;
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()
	}
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值