黑猴子的家:Scala 继承类

和Java一样使用extends关键字,在定义中给出子类需要而超类没有的字段和方法,或者重写超类的方法。

1、extends

class Father {
  def shout(msg: String): Unit ={
    println("Father中的shout方法调用" + msg)
  }
}

//使用extends 关键字 继承 父类
//父类 非抽象的 需要用 override关键字
class Child extends Father{
  override def shout(msg: String): Unit = {
    println("Child中的shout方法调用" + msg)
  }
}

object ChildMain {
  def main(args: Array[String]): Unit = {
    val father = new Father
    val child = new Child

    father.shout("hahaha")
    child.shout("xixixi")
  }
}

尖叫提示:如果类声明为final,他将不能被继承。如果单个方法声明为final,将不能被重写

2、继承加混入特质

class AFather {

}

trait Adminal{
  var leg:Int = _
}

trait Victor{
  val bo:Int
}

//一个类只能继承一个父类,可以混入多个特质
//当不继承父类,但需要混入特质的时候,第一个关键字,使用extends,后跟with关键字
class Dog extends AFather with Adminal with Victor{
  override val bo: Int = 6
}

3、没有继承,只混入特质,依然使用extends关键字

class AFather {

}

trait Adminal{
  var leg:Int = _
}

trait Victor{
  val bo:Int
}

//一个类只能继承一个父类,可以混入多个特质
//当不继承父类,但需要混入特质的时候,第一个关键字,使用extends,后跟with关键字
class Dog extends Adminal with Victor{
  override val bo: Int = 6
}

转载于:https://www.jianshu.com/p/edb46628b37b

猜你喜欢

转载自blog.csdn.net/weixin_34198762/article/details/91182490