You can only do this by exposing another property (or function) in Dogs that accesses the super class property to get the value being held in that field, and using that:
private class Dogs(var breed: String) : Animals() {
override var color: String = "Black"
var animalColor: String
get() = super.color
set(value) {
super.color = value
}
}
But this is an abuse of inheritance, and runs counter to common expectations of OOP. A single property should not have a different meaning in a subclass, such that external classes have to distinguish between them. If Dogs has some characteristic that is different than the property in Animals, then it should have a new, different property for that rather than overriding.
Also, you don't need to override just to change the initial value of a var
. Overriding creates a second, redundant backing field. Your Dogs class should be like this if you want Dogs to have a different default value for color
:
private class Dogs(var breed: String) : Animals() {
init {
color = "Black"
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…