Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

how to access parent class variable from child if it is overriden it in child class in kotlin

I want to access animals class color from dogs reference
as I am new to kotlin if something is wrong guide me

fun main() {

    var dogs = Dogs("pug")
    println("Color of Dog :${dogs.color}")//Black
    println("Color of Animal:${}")//White
}

private open class Animals {
    open var color: String = "White"
}

private class Dogs(var breed: String) : Animals() {
    override var color: String = "Black"
}
question from:https://stackoverflow.com/questions/65839402/how-to-access-parent-class-variable-from-child-if-it-is-overriden-it-in-child-cl

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...