[英]Is there a way to share data between an abstract class and it's implementation classes without using companion object in Kotlin
I have a class called Animal
which is an abstract class.我有一个名为Animal
的类,它是一个抽象类。
abstract class Animal {
protected var totalAnimals = 0
fun provideTotalAnimals(totalAnimals: Int) {
this.totalAnimals = totalAnimals
}
}
Now there is another class that is extending Animal
says a Dog
现在有另一个类正在扩展Animal
says a Dog
class Dog: Animal() {
fun printTotalDogsAndAnimals(totalDogs: Int) {
val totalAnimals = totalDogs + totalAnimals
println("Total Animals: $totalAnimals")
}
}
Since I'm extending the Animal
class I'm able to get hold of the totalAnimals
.由于我正在扩展Animal
类,因此我能够掌握totalAnimals
。 But, the problem is that totalAnimals
will be always 0 no matter what.但是,问题在于,无论如何, totalAnimals
将始终为 0。 I fixed this by putting the totalAnimals
inside a companion object in the Animal
class.我通过将totalAnimals
放在Animal
类的伴生对象中来解决这个问题。 But, I would like to know is there a better way to share the data from an abstract class and its implementation classes without using a companion object.但是,我想知道是否有更好的方法来共享来自抽象类及其实现类的数据,而不使用伴随对象。 A better way to design my classes is what I'm looking at.我正在研究一种更好的方式来设计我的课程。
You should override abstract class's function to set totalAnimals value.您应该重写抽象类的函数来设置 totalAnimals 值。 In your case, you are adding some value to 0 and printing it.在您的情况下,您正在为 0 添加一些值并打印它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.