简体   繁体   English

有没有办法在抽象类和它的实现类之间共享数据而不使用 Kotlin 中的伴随对象

[英]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.

相关问题 Kotlin 在抽象类中调用伴随对象 - Kotlin Calling Companion Object in Abstract Class 使用伴侣对象返回Kotlin中的类的实例 - Using companion object to return an instance of the class in Kotlin 不使用单例的类之间共享数据的方法 - A way to share data between classes not using singleton 在不使用受保护的情况下处理抽象类的正确方法是什么? - What's the correct way to handle abstract classes without using protected? 在具体的JPA类之间共享Java实现的最佳方法? - Best way to share Java implementation between concrete JPA classes? 在两个或多个类之间共享同一接口实现的有效方法 - Efficient way to share the same interface implementation between two or more classes Java静态方法和Kotlin随播对象有什么区别? 为什么在Andorid数据绑定中出现错误? - What is the difference between Java static method and Kotlin companion object ? Why it is giving error in Andorid Data Binding? 如何覆盖从 java class 在 kotlin 伴侣 ZA8CFDE6331BD59EB6AC96F8911C4 - How to override inherited getter from java class in a kotlin companion object kotlin抽象静态乐趣在伴侣对象 - kotlin abstract static fun in companion objects 在不同的JUnit测试类之间共享数据的最佳方法是什么 - What is the best way to share data between different JUnit test classes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM