关闭

0015.scala的多重继承、多重继承构造器执行顺序、基于trait的AOP实现

标签: scalascala spark
314人阅读 评论(0) 收藏 举报
分类:
1.scala的多重继承
package com.jn.scala

/**
* Created by admin on 2015/11/12.
*/
class Human{
 
println(
"Human")
}

trait TTeacher extends Human{
 
println(
"TTeacher")
 
def teach
}
trait PianoPlay extends Human{
 
println(
"PianoPlay")
 
def playPiano = {println( "I'm playing piano")}
}
class PianoTeacher extends Human with TTeacher with PianoPlay{//构造器初始化顺序,从左边到右边,已经加载的,不会重复加载
 
override def teach = {println( "I'm training students")}
}

object UseTrait2 {
 
def main(args: Array[String ]) {
   
val t1 = new PianoTeacher
    t1.playPiano
    t1.teach

  }
}

//运行结果
Human
TTeacher
PianoPlay
I'm playing piano
I'm training students
例2:
package com.jn.scala

/**
* Created by admin on 2015/11/12.
*/
class Human{
 
println(
"Human")
}

trait TTeacher extends Human{
 
println(
"TTeacher")
 
def teach
}
trait PianoPlay extends Human{
 
println(
"PianoPlay")
 
def playPiano = {println( "I'm playing piano")}
}
class PianoTeacher extends Human with TTeacher with PianoPlay{
 
override def teach = {println( "I'm training students")}
}

object UseTrait2 {
 
def main(args: Array[String ]) {
//    val t1 = new PianoTeacher
//    t1.playPiano
//    t1.teach
   
val t2 = new Human with TTeacher with PianoPlay{ //匿名类进行实现需要重写没有实现的接口teach
     
override def teach = {println( "I'm teaching students")}
}
    t2.playPiano
    t2.teach


  }
}

//运行结果
Human
TTeacher
PianoPlay
I'm playing piano
I'm teaching students

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:65542次
    • 积分:1736
    • 等级:
    • 排名:千里之外
    • 原创:115篇
    • 转载:3篇
    • 译文:0篇
    • 评论:4条
    最新评论