/** * 主构造器直接定义在类名称的后面,参数列表和类名写在一起 * 主构造器的参数会自动提升为对象的属性,不需要在对象中重新定义一遍 */ class Student(val id: Int, name: String) { println("主构造器开始执行") //Student类的私有属性 private val city = "beijing" //调用object Student的私有属性 def events() = println(Student.job + "在" + city) var hobby: String = "basketball" def sayHello = println("hello") println("主构造器执行结束") // 辅助构造器 def this(id: Int, name: String, hobby: String) { //todo 辅助器的第一行必须调用主构造器或者其他已经存在的辅助构造器 this(id, name) this.hobby = hobby } } /** * 如果有一个class文件,还有一个与class同名的object文件,那么就称这个object是class的伴生对象,class是object的伴生类 * 所以这里class Student就是object Student的伴生类,object Student就是class Student的伴生对象 */ object Student { //object Student的私有属性 private val job = "秃头侠" def main(args: Array[String]): Unit = { val zhangsan = new Student(1, "zhangsan") zhangsan.sayHello println("===============================") val lisi = new Student(2, "lisi", "PC-Game") lisi.sayHello println("lisi的id为" + lisi.id + ",lisi的hobby为" + lisi.hobby) println("===============================") /** * 1.伴生类和伴生对象必须存放在一个.scala文件中 * 2.伴生类和伴生对象的最大特点就是可以相互访问 */ //调用class Student的私有属性 val student = new Student(3, "一拳超人") student.events() println(student.city + "有" + job) } }
控制台输出结果:

主构造器开始执行
主构造器执行结束
hello
===============================
主构造器开始执行
主构造器执行结束
hello
lisi的id为2,lisi的hobby为PC-Game
===============================
主构造器开始执行
主构造器执行结束
秃头侠在beijing
beijing有秃头侠

相关文章:

  • 2022-02-26
  • 2021-05-30
  • 2021-07-06
  • 2021-12-28
  • 2021-07-18
  • 2021-12-13
  • 2021-06-12
  • 2022-02-01
猜你喜欢
  • 2022-12-23
  • 2021-08-07
  • 2021-09-26
  • 2021-10-29
  • 2021-07-10
  • 2022-12-23
  • 2021-11-16
相关资源
相似解决方案