大三寒假学习 spark学习 Scala面向对编程 类(构造器)

构造器:

  • Scala构造器包括一个主构造器,和若干个辅助构造器。
  • 辅助构造器的名称为this,每个辅助构造器必须调用一个之前已经定义的辅助构造器或者主构造器。
class counter {
private var value= 0//value用来存储计数器的起始值
private var name=""//表示计数器的名称
private var mode = 1 //mode用来表示计数器类型(比如,1表示步数计数器,2表示时间计数器)
def this(name: string){
//第一个辅助构造器
this()//调用主构造器
this.name = name
}
def this (name: string,mode: Int){ 
//第二个辅助构造器
this(name)//调用前一个辅助构造器
this.mode = mode
}
def increment(step: Int): unit= { value += step}
def current(): Int = {value} def info(): unit = {printf("Name:%s and mode is %d\n", name,mode)} } object MyCounter{ def main(args:Array[string]){ val mycounter1 = new Counter //主构造器 val myCounter2 = new Counter( "Runner")//第一个辅助构造器,计数器的名称设置为Runner,用来计算跑步步数 val mycounter3 = new Counter("Timer",2)//第二个辅助构造器,计数器的名称设置为Timer,用来计算秒数 mycounter1.info//显示计数器信息 mycounter1.increment(1)//设置步长 printf("current value is:%d\n",mycounter1.current)//显示计数器当前值mycounter2.info//显示计数器信息 mycounter2.increment(2)//设置步长 printf("current Value is: %d\n" ,mycounter2.current)//显示计数器当前值mycounter3.info//显示计数器信息 mycounter3.increment(3)//设置步长 printf("current Value is:%d\n",mycounter3.current)//显示计数器当前值 } }

  • Scala的每个类都有主构造器。但是,Scala的主构造器和Java有着明显的不同Scala的主构造器是整个类体,需要在类名称后面罗列出构造器所需的所有参数,这些参数被编译成字段,字段的值就是创建对象时传入的参数的值。

  下面为代码示例 

class counter(val name: string, val mode: Int){
private var value = 0//value用来存储计数器的起始值def increment(step: Int): unit = { value += step}def current(): Int = {value}
def info():unit = {printf("Name:%s and mode is %d\n" , name,mode)}
}
object Mycounter{
def main(args :Array[string]){
val mycounter = new Counter( "Timer",2)mycounter.info//显示计数器信息
mycounter.increment(1) //设置步长
printf("current value is: %d\n",mycounter.current)//显示计数器当前值
}
原文地址:https://www.cnblogs.com/fengchuiguobanxia/p/15790355.html