关闭

scala学习trait

2370人阅读 评论(0) 收藏 举报
分类:

Scala里相当于Java接口的是Trait(特征)。Trait的英文意思是特质和性状),实际上他比接口还功能强大。与接口不同的是,它还可以定义属性和方法的实现。Scala中特征被用于服务于单一目的功能模块的模块化中。通过混合这种特征(模块)群来实现各种应用程序的功能要求,Scala也是按照这个构想来设计的。

一般情况下Scala的类只能够继承单一父类,但是如果是特征的话就可以继承多个,从结果来看就是实现了多重继承。


trait Action{
def doAction
}
trait TBeforeAfter extends Action{
abstract override def doAction{
println("initialization")
super.doAction
println("Destory")
}
}
class Work extends Action{
override def doAction=println("working...")
}


class Human{
println("Human")
}
trait TTeacher extends Human{
println("TTeacher")
def teach
}
trait PianoPlayer extends Human{
println("PianoPlayer")
def playPiao={
println("I am playing piano.")
}
}


class PianoTeacher extends Human with TTeacher with PianoPlayer{
override def teach={
println("I am training students.")
}
}




object AopTest{
def main(args:Array[String]){


val work=new Work with TBeforeAfter
work.doAction
//initialization
//working...
//Destory


val t1=new PianoTeacher
t1.playPiao
t1.teach
//Human
//TTeacher
//PianoPlayer
//I am playing piano.
//I am training students.


val t2=new Human with TTeacher with PianoPlayer{
def teach={println("I am teaching students")}
}
t2.playPiao
t2.teach
//Human
//TTeacher
//PianoPlayer
//I am playing piano.
//I am teaching students.
}
}



class AbstractClassOps{
var id:Int=_
//val id:Int=_    //错误
}
abstract class SuperTeacher(val name:String){
var id:Int
var age:Int
def teach
}
class TeacherForMaths(name:String) extends SuperTeacher(name){
override var id=name.hashCode()
override var age=22
override def teach{
println("Teaching!!")
}
}
object AbstractClassOps{
def main(args:Array[String]){
val teacher=new TeacherForMaths("spark")
teacher.teach


println(teacher.id)
println(teacher.name)
}
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:277567次
    • 积分:4077
    • 等级:
    • 排名:第7595名
    • 原创:124篇
    • 转载:110篇
    • 译文:0篇
    • 评论:8条
    最新评论