有没有一种方法可以在摘要类之间共享数据,而IT and It and Ithermant of Companion Object in kotlin中的实现类别
我有一个称为动物
的类,这是一个抽象类。
abstract class Animal {
protected var totalAnimals = 0
fun provideTotalAnimals(totalAnimals: Int) {
this.totalAnimals = totalAnimals
}
}
现在,还有另一个正在扩展Animal
的课程说dog
,
class Dog: Animal() {
fun printTotalDogsAndAnimals(totalDogs: Int) {
val totalAnimals = totalDogs + totalAnimals
println("Total Animals: $totalAnimals")
}
}
因为我正在扩展Animal
类,所以我能够掌握TotalAnimals
。但是,问题在于totalAnimals
无论如何都将始终为0。我通过将TotalAnimals
放入Animal
类中的伴侣对象中来解决此问题。但是,我想知道,没有使用伴随对象的情况下,有一种更好的方法来共享抽象类及其实现类的数据。我正在考虑的更好的设计课程方法。
I have a class called Animal
which is an abstract class.
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
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
. But, the problem is that totalAnimals
will be always 0 no matter what. I fixed this by putting the totalAnimals
inside a companion object in the Animal
class. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该覆盖抽象类的功能来设置taterAnimals值。在您的情况下,您将一些值添加到0并打印它。
You should override abstract class's function to set totalAnimals value. In your case, you are adding some value to 0 and printing it.