说明
多态是面向对象编程的特性之一,是建立在 继承 之上的,含义:
- 父类的引用,可以指向子类的对象
- 在运行时,才能决定 该引用是子类对象 还是父类对象
案例
class Phone {
val cpu:String = "111"
def call(num:String):Unit = {
println("用 "+cpu+" 给 "+num+" 打电话")
}
}
class IPhone extends Phone {
override val cpu:String = "A15" //覆盖父类的属性
override def call(num:String):Unit = { //覆盖父类的方法
println("子类===用 "+cpu+" 给 "+num+" 打电话")
}
}
object Phone{
def main(args: Array[String]): Unit = {
val phone:Phone = new IPhone //父类的引用,可以指向子类的对象
println(phone.cpu) //在运行时,才能决定 父类引用,其实是子类对象,即:访问子类属性
phone.call("120") //在运行时,才能决定 父类引用,其实是子类对象,即:调用子类方法
}
}
执行结果:
A15
子类===用 A15 给 120 打电话