Kotlin:在扩展类之间的抽象类中共享变量

问题描述 投票:0回答:1

我有一个抽象类A,其类B和C正在扩展。我想在类A中有一个静态变量,我可以从B和C中获取并设置它,以便它们访问共享的值。当前,使用getter和setter的B和C都有自己的变量实例。

老实说,我不太在乎好的或坏的做法,我只是想让它以某种方式起作用。

java kotlin inheritance architecture abstract
1个回答
0
投票

0
投票

您可以使用companion object模拟静态变量:

abstract class A {

    companion object {
        var staticVariable: Int = 0
    }
}

class B : A() {
    fun updateStaticVariable() {
        staticVariable = 1
    }
}

class C : A() {
    fun updateStaticVariable() {
        staticVariable = 2
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.