給定一個抽象類:
abstract class BobaTea {
abstract val sweetness: Int
}
我有一個要覆寫的子類sweetness,但是我想在建構式中這樣做,因為甜蜜的值不能在編譯時定義,我只會在運行時知道它。但是,我的建構式將確保子類的所有實體都確實實作了抽象值sweetness。
class MatchaBobaLatte : BobaTea() {
constructor(sweetness: Int) : this() {
this.sweetness = sweetness // This fails with "val cannot be reassigned"
}
}
為什么這不起作用?我沒有重新分配 sweetness,我只是重寫它,因為它在超類中是抽象的。
謝謝。
uj5u.com熱心網友回復:
覆寫抽象屬性要求您在頂層覆寫它并在override val某處提及。
它可以發生在主建構式中,例如
class MatchaBobaLatte(override val sweetness: Int) : BobaTea() {
// ...
}
或通過顯式宣告覆寫 val 之類的
class MatchaBobaLatte : BobaTea {
override val sweetness: Int
constructor(sweetness: Int) : super() { // Not this()!
this.sweetness = sweetness
}
}
或喜歡
class MatchaBobaLatte(sweetness: Int) : BobaTea() {
// primary constructor parameters are available for instance
// initializer code
override val sweetness = sweetness * 2
}
您看到的錯誤是多種因素組合的結果。您嘗試委托給一個this()不存在的主建構式,但它將是需要設定所有val值的主建構式。如果您愿意,也會出現該錯誤
class Reassign {
val sweetness: Int; // when no value here, then
// primary ctor must init all vals or you get
// "Property must be initialized or be abstract"
constructor() {
sweetness = 42;
}
// can't touch vals in here any more because it runs
// after "this()"
constructor(foo: Int) : this() {
sweetness = foo; // Val cannot be reassigned
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/525731.html
標籤:爪哇科特林哎呀遗产抽象类
