Scala学习笔记12【继承、抽象类、trait实战】

Scala 继承

代码示例:

class Father(val name: String, val age: Int){
  println("Father is here.")

  val school = "CSU"

  def sleepTime = "8 hours"

  //重定义已有方法,加上override
  override def toString = "Father."
}

//子类Son有自己的number成员,继承父类的(name, age)构造器,必须加上父类构造器
class Son(name: String, age: Int, val number: String) extends Father(name, age){
  println("Son is here.")

  //override重定义父类中已有成员
  override val school = "HNU"

  //super引用父类成员的值
  override def toString = "My super class is " + super.toString() + "sleep " + super.sleepTime
}


object ScalaTest {
  def main(args: Array[String]){
    val f = new Father("Lao zhang", 48) //执行后会产生Father is here.
    val s = new Son("Zhang san", 24, "001")//执行后会产生 Father is here. Son is here.

    println("Father's school is " + f.school)
    println("Son's school is " + s.school)
    println
    println("Father's toString is " + f.toString)
    println("Son's toString is " + s.toString)
    println
    println("Son's number is " + s.number)
  }
}

运行结果:

Father is here.
Father is here.
Son is here.
Father's school is CSU
Son's    school is HNU

Father's toString is Father.
Son's    toString is My super class is Father.sleep 8 hours

Son's number is 001

抽象类

代码示例:

//abstract关键字声明抽象类
abstract class SuperTeacher(val name: String){
    //默认可不设初值
  var id: Int
  var age: Int

  //抽象方法定义
  def teach
}

class MathsTeacher(name: String) extends SuperTeacher(name){
  //override可选, 建议加上
  override var id = 10001
  override var age = 25

  override def teach{
    println("Teaching maths.")
  }
}

object ScalaAbstractClassTest {
  def main(args: Array[String]){
    val teacher = new MathsTeacher("Lao Zhang")

    println("teacher.name:"+ teacher.name)
    println("teacher.id :"+ teacher.id)
    teacher.teach
  }
}

运行结果:

teacher.name:Lao Zhang
teacher.id  :10001
Teaching maths.

trait使用方法实战

trait字面意思是特质或者特征,和java,c#中接口很类似。
但是trait支持部分实现,也就是说可以在scala的trait中可以实现部分方法。
Java中使用implements实现接口,Scala中用关键字extends实现trait。

程序示例:

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

class Scala extends Logger{
  override def log(msg: String) = println("msg is " + msg)

  def printOut{
    log("Scala extends Logger")
  }
}

//提供已实现方法的trait
trait Logger2 extends Logger{
  override def log(msg: String){
    println("Logger2 msg is " + msg)
  }
}


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

        //调用未实现方法的trait--Logger
    val a = new Scala
    a.printOut

    //调用已实现方法的trait--Logger2
    val b = new Scala with Logger2
    b.printOut
  }
}

运行结果:

msg is Scala extends Logger
Logger2 msg is Scala extends Logger

你可能感兴趣的:(scala,继承,抽象类,trait)