spark编程基础--2.3面向对象编程基础

类 对象 继承 参数化类型 特质 模式匹配(match case类) 包 

类的定义

 

构造器

//代码文件为/usr/local/scala/mycode/Counter2.scala
class Counter {
    private var value = 0 
    private var name = ""
private var step = 1 //计算器的默认递进步长
println("the main constructor")
    def this(name: String){ //第一个辅助构造器
        this() //调用主构造器
        this.name = name
           printf("the first auxiliary constructor,name:%s\n",name)
    }
    def this (name: String,step: Int){ //第二个辅助构造器
        this(name) //调用前一个辅助构造器
        this.step = step
printf("the second auxiliary constructor,name:%s,step:%d\n",name,step)
    }
    def increment(step: Int): Unit = { value += step}
    def current(): Int = {value}
}

 

单例对象

//代码文件为/usr/local/scala/mycode/Person1.scala
class Person(val name:String){
    private val id = Person.newPersonId() //调用了伴生对象中的方法
    def info() {
        printf("The id of %s is %d.\n",name,id)
    }
}
object Person {
    private var lastId = 0  //一个人的身份编号
    def newPersonId() = {
        lastId +=1
        lastId
    }
    def main(args: Array[String]) {
        val person1 = new Person("Lilei")
        val person2 = new Person("Hanmei")
        person1.info()
        person2.info()
    }
}

 

 

特质

//代码文件为/usr/local/scala/mycode/Bird2.scala
trait Flyable {
        var maxFlyHeight:Int  //抽象字段
     def fly() //抽象方法
def breathe(){ //具体的方法
         println("I can breathe")
     }
 }
trait HasLegs {
        val legs:Int   //抽象字段
     def move(){printf("I can walk with %d legs",legs)}
   }
class Animal(val category:String){
    def info(){println("This is a "+category)}
}
class Bird(flyHeight:Int) extends Animal("Bird") with Flyable with HasLegs{
var maxFlyHeight:Int = flyHeight //重载特质的抽象字段
val legs=2 //重载特质的抽象字段
     def fly(){
printf("I can fly at the height of %d",maxFlyHeight)
}//重载特质的抽象方法
}

 

match语句

//代码文件为/usr/local/scala/mycode/TestMatch1.scala
import scala.io.StdIn._
println("Please input a country:")
val country=readLine()
country match{
        case "China" => println("中国")
        case "America" => println("美国")
        case "Japan" => println("日本")
        case _ => println("我不认识!")
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值