面试题答案
一键面试// 定义Shape抽象类,包含抽象的draw方法
abstract class Shape {
abstract fun draw()
}
// Circle类继承自Shape类,实现draw方法
class Circle : Shape() {
override fun draw() {
println("绘制圆形")
}
}
// Rectangle类继承自Shape类,实现draw方法
class Rectangle : Shape() {
override fun draw() {
println("绘制矩形")
}
}
在多态调用时,Kotlin编译器基于对象的实际类型(运行时类型)来解析方法。例如:
fun main() {
val shape1: Shape = Circle()
val shape2: Shape = Rectangle()
shape1.draw()
shape2.draw()
}
在上述代码中,shape1
和shape2
声明类型为Shape
,但实际类型分别为Circle
和Rectangle
。当调用draw
方法时,Kotlin编译器在运行时根据对象实际类型来调用对应的draw
实现,即Circle
的draw
和Rectangle
的draw
,这就是多态的体现。编译器在编译期只确保调用的方法存在于声明类型的接口或父类中,运行时才确定具体执行的方法版本。