五、按要求编写程序: (1)编写抽象类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-26 18:36:05 浏览: 20
好的,以下是符合要求的Java程序:
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 run very fast.");
}
@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 swim in the sea.");
}
@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;
public class Test {
public static void main(String[] args) {
ArrayList<Mammal> list = new ArrayList<>();
list.add(new Cheetah());
list.add(new Dolphin());
list.add(new Bat());
for (Mammal mammal : list) {
mammal.move();
mammal.eat();
System.out.println();
}
}
}
```
在这个程序中,Mammal类是一个抽象类,它有两个抽象方法move()和eat()。Cheetah、Dolphin、Bat三个类都继承自Mammal类,并实现了move()和eat()方法。Test类中创建了一个ArrayList对象list,将Cheetah、Dolphin、Bat的对象分别存入list中,并使用for-each循环遍历list中的元素,多态地调用move()和eat()方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)