Kotlin:在扩展 classes 之间共享抽象 class 变量
Kotlin: share variable in abstract class between extending classes
我有一个摘要 class A,其中 classes B 和 C 正在扩展。
我想在 class A 中有一个静态变量,我可以从 B 和 C 获取和设置它,以便它们访问共享值。
目前,使用 getters 和 setters B 和 C 都有自己的变量实例。
老实说,我不太在意练习的好坏,我只是想让它以某种方式发挥作用。
可以使用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
}
}
要从其他地方访问它:
val sv = A.staticVariable
if (sv == 0) {
//...
}
我有一个摘要 class A,其中 classes B 和 C 正在扩展。 我想在 class A 中有一个静态变量,我可以从 B 和 C 获取和设置它,以便它们访问共享值。 目前,使用 getters 和 setters B 和 C 都有自己的变量实例。
老实说,我不太在意练习的好坏,我只是想让它以某种方式发挥作用。
可以使用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
}
}
要从其他地方访问它:
val sv = A.staticVariable
if (sv == 0) {
//...
}