有没有一种方法可以在摘要类之间共享数据,而IT and It and Ithermant of Companion Object in kotlin中的实现类别

发布于 2025-02-06 09:01:31 字数 711 浏览 2 评论 0原文

我有一个称为动物的类,这是一个抽象类。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初见 2025-02-13 09:01:31

您应该覆盖抽象类的功能来设置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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文