编写抽象类Mammal(哺乳动物),拥有抽象方法void move()和void eat (); (2)维承Mammal类编写 Cheetah(猎豹)、Dolphin(海豚)、Bat(蝙蝠)三个类,分别为它们编写move()和eat()方法覆盖父类中的同名方法,方法被调用后在命令行中输出合适的内容。(如Bat的move()方法输出“I’m flying.”,eat()方法输出“I eat insect.”) (3)创建包含main方法的Test类,在main方法中创建专门用于存储Mammal对象的Arravlist<Mammal> list,并创建Cheetah、Dolphin、Bat 对象各一个,存入list,最后用遍历list,并用多态方式调用对象中的move()和eat()方法。
时间: 2024-03-22 19:37:41 浏览: 53
day03-内部类&API1
好的,以下是代码实现:
Mammal.java
```java
public abstract class Mammal {
public abstract void move();
public abstract void eat();
}
```
Cheetah.java
```java
public class Cheetah extends Mammal {
@Override
public void move() {
System.out.println("I'm running.");
}
@Override
public void eat() {
System.out.println("I eat meat.");
}
}
```
Dolphin.java
```java
public class Dolphin extends Mammal {
@Override
public void move() {
System.out.println("I'm swimming.");
}
@Override
public void eat() {
System.out.println("I eat fish.");
}
}
```
Bat.java
```java
public class Bat extends Mammal {
@Override
public void move() {
System.out.println("I'm flying.");
}
@Override
public void eat() {
System.out.println("I eat insects.");
}
}
```
Test.java
```java
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Mammal> list = new ArrayList<>();
Cheetah cheetah = new Cheetah();
Dolphin dolphin = new Dolphin();
Bat bat = new Bat();
list.add(cheetah);
list.add(dolphin);
list.add(bat);
for (Mammal mammal : list) {
mammal.move();
mammal.eat();
}
}
}
```
运行结果:
```
I'm running.
I eat meat.
I'm swimming.
I eat fish.
I'm flying.
I eat insects.
```
阅读全文