抽象类练习: 不同动物进食的方式不同,例如蛇吞,牛咀嚼。(1)定义抽象的动物类Animal,包含抽象方法eating(String food)方法;(2)定义动物子类牛、蛇等,重写父类动物的eating()方法实现不同动物不同的进食方式;(3)定义Living类,定义方法toEating(Animal animal,String food),测试不同动物的进食方式。测试结果如图所示。要求先画出类结构图,然后编写Java程序。
时间: 2023-11-27 09:52:30 浏览: 84
关于抽象类的java实验 Animal
类结构图如下:
```
+--------------+
| Animal |
+--------------+
| + eating() |
+--------------+
^
|
+--------------+
| Snake |
+--------------+
| + eating() |
+--------------+
^
|
+--------------+
| Cow |
+--------------+
| + eating() |
+--------------+
^
|
+--------------+
| Living |
+--------------+
| + toEating() |
+--------------+
```
代码实现如下:
```java
// Animal.java
public abstract class Animal {
public abstract void eating(String food);
}
// Snake.java
public class Snake extends Animal {
@Override
public void eating(String food) {
System.out.println("蛇吞" + food);
}
}
// Cow.java
public class Cow extends Animal {
@Override
public void eating(String food) {
System.out.println("牛咀嚼" + food);
}
}
// Living.java
public class Living {
public void toEating(Animal animal, String food) {
animal.eating(food);
}
}
// Main.java
public class Main {
public static void main(String[] args) {
Living living = new Living();
Animal snake = new Snake();
Animal cow = new Cow();
living.toEating(snake, "老鼠");
living.toEating(cow, "草");
}
}
```
运行结果如下:
```
蛇吞老鼠
牛咀嚼草
```
阅读全文