27.scala编程思想笔记——辅助构造器

来源:互联网 发布:哈佛 知乎 编辑:程序博客网 时间:2024/04/28 20:23

27.scala编程思想笔记——辅助构造器

         欢迎转载,转载请标明出处:http://blog.csdn.net/notbaron/article/details/50445768
源码下载连接请见第一篇笔记。

类参数列表中的具名参数和缺省参数使我们可以按照多种方式构造对象,而且可以通过创建多个构造器来使用构造器重载机制。

         要想创建重载的构造器,需要定义多个称为this的方法。

         重载构造器在Scala中有一个特殊的名字:辅助构造器。

         构造器负责执行初始化中重要的动作,因此构造器重载机制有一个额外的限制:所有辅助构造器必须首先调用主构造器,即按照类参数列表和类体而产生的构造器。要想在辅助构造器中调用主构造器,需要使用this关键字而不是类名。

例如:

import com.atomicscala.AtomicTest._

 

class GardenGnome(val height:Double,

  valweight:Double, val happy:Boolean) {

 println("Inside primary constructor")

  var painted =true

  defmagic(level:Int):String = {

    "Poof!" + level

  }

  defthis(height:Double) {

   this(height, 100.0, true)

  }

  defthis(name:String) = {

    this(15.0)

    painted istrue

  }

  defshow():String = {

    height +" " + weight +

    "" + happy + " " + painted

  }

}

 

new GardenGnome(20.0, 110.0, false).

show() is "20.0 110.0 false true"

new GardenGnome("Bob").show() is

"15.0 100.0 true true"

执行如下:

[root@OEL examples]# scala GardenGnome.scala

Inside primary constructor

20.0 110.0 false true

Inside primary constructor

true

15.0 100.0 true true

0 0
原创粉丝点击