1、代码如下
package com.yy.oop
//父类Animal
class Animal(val name:String,val weight:Int){
println("this is the constructor of Animal.")
val height = "100"
def walk(){
println(" can walk.")
}
}
/**
* 子类Tiger继承父类Animal
* 子类构造成员必须覆盖父类的构造成员
* 重写时,使用override
*/
class Tiger(name:String,weight:Int,val color:String)extends Animal(name,weight){
println("this is the construtor of Tiger.")
//重写
override val height = "200"
//重写
override def walk(){
//自己实现
print(name)
//调用父类方法
super.walk()
}
}
object ExtendsClassTest {
def main(args: Array[String]): Unit = {
//实例化子类
val tiger = new Tiger("Tiger",300,"yellow")
println("Tiger Height:" + tiger.height)
tiger.walk()
}
}
2、结果如下
this is the constructor of Animal.
this is the construtor of Tiger.
Tiger Height:200
Tiger can walk.
从上面可以看出:
当实例化子类时,先执行父类的构造方法,再执行子类的构造方法。