码迷,mamicode.com
首页 > 其他好文 > 详细

[Scala基础系列 08]Scala继承、抽象类、接口trait以及AOP实现

时间:2015-08-11 20:56:43      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

1.继承

和java一样,scala采用extends关键字继承基类。代码实例如下:

/**
* Created by molyeo on 2015/8/11.
*/
class Person(val name: String, var age: Int) {
  println("The primary constructor of Person")
  val school = "BJU"
  def sleep = "8 hours"
  override def toString = "I am a Person1!"
}

class Worker(name: String, age: Int, val salary: Long) extends Person(name, age) {
  println("This is the subClass of Person, Primary constructor of Worker")
  override val school = "Spark"
  override def toString = "I am a Worker!" + super.sleep
}

object OverrideOperations {
  def main(args: Array[String]) {
    val w = new Worker("Spark", 25, 100000)
    println("School :" + w.school)
    println("Salary :" + w.salary)
    println(w.toString())
  }
}

子类重写基类字段和方法,添加override即可,本程序先调用基类Person的构造函数,然后调用子类Worker的构造函数,并在子类中调用父类的sleep方法,故运行结果如下

The primary constructor of Person
This is the subClass of Person, Primary constructor of Worker
School :Spark
Salary :100000
I am a Worker!8 hours

2.抽象类

抽象类中只用定义字段和相关方法,然后子类实现即可。

class AbstractClassOps{
    var 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 = 29
  override def teach{
    println("Teaching!!!")
  }
}

object AbstractClassOps{
  def main(args: Array[String]) {
      val teacher = new TeacherForMaths("Spark")
      teacher.teach
      println("teacher.id" + ":" + teacher.id)
      println(teacher.name + ":" + teacher.age)
  }
}

将输入参数"Spark"的hashcode作为对象的id,故运行结果如下:

Teaching!!!
teacher.id:80085693
Spark:29

3.接口Trait

3.1.传统接口trait

package com.tv189.test

/**
 * Created by molyeo on 2015/8/11.
 */

class UseTrait {

}

trait Logger {
  def log(msg: String)
}

class ConcreteLogger extends Logger with Cloneable {
  override def log(msg: String) = println("Log: " + msg)
  def concreteLog {
    log("It‘s me !!!")
  }
}
object UseTrait extends App {
  val logger = new ConcreteLogger
  logger.concreteLog
}

ConcreteLogger实现了Logger的log方法,故输出结果显而易见:

 log("It‘s me !!!")

3.2.混入对象的trait

与java的interface有明显区别的是,trait可以有具体的方法,如若将上述代码修改如下:

package com.tv189.test

/**
 * Created by molyeo on 2015/8/11.
 */

class UseTrait {

}

trait Logger {
//  def log(msg: String)
  def log(msg: String){}
}

class ConcreteLogger extends Logger with Cloneable {
//  override def log(msg: String) = println("Log: " + msg)
  def concreteLog {
    log("It‘s me !!!")
  }
}

trait TraitLogger extends Logger {
  override def log(msg: String) {
    println(" TraitLogger Log content is : " + msg)
  }
}

object UseTrait extends App {
//  val logger = new ConcreteLogger
//  logger.concreteLog

  val logger=new ConcreteLogger with TraitLogger
  logger.concreteLog

}

则程序输出为:

TraitLogger Log content is : It‘s me !!!

程序实际上是将TraitLogger这个trait混入到具体的对象logger中。

4.多重继承的执行顺序

scala对于多重继承会从左到右进行构造,如果左边的接口已经构建过,则后续的接口不会重复构建,这点和java有很大的不同。如下述程序

package com.tv189.test

/**
 * Created by molyeo on 2015/8/11.
 */

class UseTrait {

}

class Human {
  println("Human")
}

trait TTeacher extends Human {
  println("TTeacher")

  def teach
}

trait PianoPlayer extends Human {
  println("PianoPlayer")

  def playPiano = {
    println("I am playing piano. ")
  }
}

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

object UseTrait extends App {
  val t = new PianoTeacher
  t.playPiano
  t.teach
}

其运行结果

Human
TTeacher
PianoPlayer
I am playing piano. 
I am training students. 

5.AOP的实现

scala中利用trait可以轻松实现AOP,如下我们在Work类doAction方法的前后打印"Initialization"和"Destroyed"内容

package com.tv189.test

/**
 * Created by molyeo on 2015/8/11.
 */

class UseTrait {

}

//AOP
trait Action {
  def doAction
}

trait TBeforeAfter extends Action {
  abstract override def doAction {
    println("Initialization")
    super.doAction
    println("Destroyed")
  }
}

class Work extends Action {
  override def doAction = println("Working...")
}


object UseTrait extends App {
  val work = new Work with TBeforeAfter
  work.doAction
}

程序输出如下

Initialization
Working...
Destroyed

 

[Scala基础系列 08]Scala继承、抽象类、接口trait以及AOP实现

标签:

原文地址:http://www.cnblogs.com/molyeo/p/4721736.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!