抽象类练习: 不同动物进食的方式不同,例如蛇吞,牛咀嚼。(1)定义抽象的动物类Animal,包含抽象方法eating(String food)方法;(2)定义动物子类牛、蛇等,重写父类动物的eating()方法实现不同动物不同的进食方式;(3)定义Living类,定义方法toEating(Animal animal,String food),测试不同动物的进食方式。测试结果如图所示。要求先画出类结构图,然后编写Java程序。
时间: 2023-11-28 21:48:05 浏览: 48
计算机后端-Java-Java核心基础-第15章 面向对象07 12. 抽象类的课后练习.avi
类结构图如下:
```
+--------+
| Animal |
+--------+
^
|
+-----------+--------------+
| |
+--------+ +-------+
| Bull | | Snake |
+--------+ +-------+
|eating()| |eating()|
+--------+ +-------+
+--------+
| Living |
+--------+
|toEating|
+--------+
```
Animal.java
```java
public abstract class Animal {
public abstract void eating(String food);
}
```
Bull.java
```java
public class Bull extends Animal {
@Override
public void eating(String food) {
System.out.println("牛咀嚼" + food);
}
}
```
Snake.java
```java
public class Snake extends Animal {
@Override
public void eating(String food) {
System.out.println("蛇吞" + food);
}
}
```
Living.java
```java
public class Living {
public void toEating(Animal animal, String food) {
animal.eating(food);
}
}
```
测试代码:
```java
public class Test {
public static void main(String[] args) {
Living living = new Living();
Animal bull = new Bull();
Animal snake = new Snake();
living.toEating(bull, "草");
living.toEating(snake, "老鼠");
}
}
```
输出结果:
```
牛咀嚼草
蛇吞老鼠
```
阅读全文