任务1:动物类 1.定义抽象动物类(Animal),属性:姓名,年龄,行为:跑步,吃饭。 2.定义猫类(Cat)继承自动物类,重写吃饭的方法,并定义该类独有的抓老鼠的方法。 3.定义狗类(Dog)继承自动物类,重写吃饭的方法,并定义该类独有的看家的方法。用scala
时间: 2024-11-12 18:45:03 浏览: 43
在Scala中,你可以按照以下步骤定义这些类:
首先,我们定义一个抽象的`Animal`类,它包含通用的属性和行为:
```scala
abstract class Animal {
val name: String
var age: Int
// 共享的行为
def run(): Unit = println(s"${name} is running.")
def eat(): Unit = println(s"${name} is eating.")
// 抽象方法,子类需要实现
abstract override def eat(customFood: String): Unit
}
```
接着,我们可以创建两个具体的子类,`Cat`和`Dog`,它们分别继承自`Animal`:
```scala
class Cat(name: String, age: Int) extends Animal {
override val age = age
override def eat(): Unit = println(s"${name} is eating fish.")
// 重写eat方法,并添加特有的行为
override def eat(customFood: String): Unit = if (customFood == "fish") super.eat else println(s"${name} doesn't like $customFood.")
// 独有的行为
def catchMice(): Unit = println(s"${name} is catching mice.")
}
class Dog(name: String, age: Int) extends Animal {
override val age = age
override def eat(): Unit = println(s"${name} is eating dog food.")
// 重写eat方法,并添加特有的行为
override def eat(customFood: String): Unit = if (customFood == "dog food") super.eat else println(s"${name} doesn't like $customFood.")
// 独有的行为
def watchHome(): Unit = println(s"${name} is watching the home.")
}
```
现在你可以创建`Cat`和`Dog`实例,展示它们的行为:
```scala
val kitty = new Cat("Kitty", 3)
kitty.run()
kitty.eat() // 输出: Kitty is eating fish.
kitty.catchMice()
val rover = new Dog("Rover", 5)
rover.run()
rover.eat() // 输出: Rover is eating dog food.
rover.watchHome()
```
阅读全文