[ad_1]
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.
[ad_2]