点击(此处)折叠或打开
- class Teacher{
- var name : String = _ //占位符
- private var age = 27 // 默认生成私有的setter、getter
- private[this] val gender = "male"
-
- //重载构造器
- def this(name : String){
- this //主构造器
- this.name = name
- }
- //重载构造器必须调用主构造器
-
- def sayHello(){
- println(this.name + ":" + this.age + ":" + this.gender);
- }
- }
点击(此处)折叠或打开
- //构造器具有参数,这些参数会成为属性
- class Teacher private (val name : String, val age : Int){//private修饰后,主构造器将不能被调用
- println("This is the primary constructor!!!")
- var gender : String = _
- println(gender)
-
- //构造时,除了方法,其他都会被实例化,所以以上步骤会执行
- def this(name : String, age : Int, gender : String){
- this(name, age)
- this.gender = gender
- }
- }
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28912557/viewspace-1827365/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/28912557/viewspace-1827365/