【发布时间】:2020-08-27 13:05:20
【问题描述】:
我正在尝试覆盖类中的值。我有以下代码:
open class Balloon() {
open var textSize: Float = 20f
init {
Log.i("textSize", textSize.toString())
}
}
class BigBalloon(): Balloon() {
override var textSize = 30f
}
但是,日志会打印出这些值:
第一个日志来自Balloon(),第二个来自BigBalloon()。当我将其覆盖为30 时,它如何打印0.0?我是否错误地实现了所有这些?
【问题讨论】:
-
我刚刚检查了你的代码,它在
println(bb.textSize)创建了一个val bb = BigBalloon()后打印了30.0。唯一的区别是我必须删除init块,因为我在没有 LogCat 的 Kotlin Playground 中尝试过... -
那么这意味着该值被正确覆盖,但不在 init 中?
-
不要在初始化块/构造函数中使用非最终属性或函数stackoverflow.com/questions/50222139/…
标签: android class kotlin inheritance