Like Java extends keyword, given subclass definition needs no fields and methods of the superclass, or superclass rewritten.
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, plus inherited trait mixed
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, not inherited, only mixed character, still use the extends keyword
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
}
Reproduced in: https: //www.jianshu.com/p/edb46628b37b