简体   繁体   中英

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.

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.

You should override abstract class's function to set totalAnimals value. In your case, you are adding some value to 0 and printing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM