【发布时间】:2018-03-02 23:14:32
【问题描述】:
我创建了一个名为 Animal 的特征和两个类,Dog 和 Cat。 Dog 和 Cat 都有存储它们拥有的生命数量的同伴类。我的 Cat 对象有 9 条生命,我的 Dog 对象有 1 条生命。我想向 Animal trait 添加一个名为 isAlive 的函数并在那里实现。 isAlive 函数需要访问 Animal 拥有的存活数。我将如何获得同伴课程中的生命值?
我应该只是将生命值移入类并删除伴随类吗?
这是我的代码。
特质
package Animal
trait Animal {
def speak: String
def getDeaths: Int
def isAlive: Boolean = {
getDeaths < 1 // I want to replace 1 with the number of lives from the Dog or Cat
}
}
猫类和同伴类
package Animal
class Cat(a: Int) extends Animal {
private var age: Int = a
private var deaths: Int = 0
def this() = this(0)
override def speak: String = {
if (this.isAlive) {
"Meow"
}
else {
"..."
}
}
// I want to do this in the trait
// override def isAlive: Boolean = this.deaths <= Cat.lives
def setAge(age: Int): Unit = this.age = age
def getAge: Int = this.age
def getDeaths: Int = this.deaths
def die(): Unit = this.deaths += 1
}
object Cat {
val lives: Int = 9
}
【问题讨论】: