首页 > 代码库 > scala构造器

scala构造器

package cn.itcast.scala.day2

/**
* Created by ZhaoXing on 2016/6/27.
*/
//跟类名交织在一起的叫 主构造器
class Student (val name: String, var age: Int, faceValue: Double = 99.99, private var height: Int = 18) {

private[this] var gender : String = null

def show(): Unit = {
//faceValue = http://www.mamicode.com/1000
println(faceValue)
}

//辅助构造器 def this (参数)
def this(name: String, age: Int, gender: String) {
//辅助构造器第一行一定要先调用主构造器
this(name, age)
this.gender = gender
}

}

object Student {

def main(args: Array[String]) {
val p = new Student("zx", 30, 100, 180)
println(p.age)
println(p.name)
p.age = 18

p.height = 199

println(p.age)

println(p.height)

//val per = new Person
//println(per)
}
}

object Main {
def main(args: Array[String]) {
val s = new Student("zx", 30, 100)
//s.height
}
}

主构造器:类中必须生命的属性,辅助构造器中有新增的必须在类中声明为属性。

 

scala构造器