原创文章,转载请注明出处!

原文地址: http://www.ptbird.cn/2016/07/19/scala-chuji-demo-06/

There I am,in the world more exciting!

by postbird

www.ptbird.cn


06类的构造器和重载构造器


 
package com.ptbird.scala /** * Created by postbird on 2016/5/25. */ class Teacher { /** * 类的构造器除了def其他的都执行 */ println("class created") var name: String = _ private var age = 27 private[this] val gender = "male" /** * 类的构造函数 需要调用一次 this */ def this(name: String) { this this.name = name } def syaHello(): Unit = { println(this.name + " : " + this.age + "--" + this.gender) } } //构造器重载 class Teacher2(name: String) { println("class 2 created") private var age = 0 def this(name: String, age: Int) { this(name) this.age = age } def syaHello(): Unit = { println(this.name + " : " + this.age) } } object ClassTest2 { def main(args: Array[String]): Unit = { var t1 = new Teacher("ptbird") // t1.syaHello() var t2 = new Teacher2("ptbird", 12) t2.syaHello() } }