用java编写编写一个类Animal,描达动物的属性和行为,通过继承Animal类定 义Bird类、Fish 类,分别描述鸟类和鱼类的属性和行为,具体要求奶下: 〈1〕Animal类定义属性namex color、fooINumber,我述动物的名称、颜色、脚的 只数;定义成员方法showInfo0,用于输出动物的属性信息;定义成员方法move0,用于描述动物如何行走(输茁“可以通过飞、跑、游等方式移动身体”, (2)通过继承Animal定 XBid类 改写交类的move万法(输出 “通过飞来移动身 体”),增加一个方法nesto用子描述在哪里筑巢: 〈3)通过继承Animal定 义Fish类 改章交爽的move方法,《綸山 “通过游米移欢身 体”,,增加一个属性length,用于指还魚的身长口改写交类的showinfo0方法,除了输出neme、colorfoo(Vumber属性,还要緰出鱼的身长 (4)编写测试类,分别创建上达B个类的对象,并给对象的所有属性赋值,调用对象的所有方法。
时间: 2024-02-22 18:59:42 浏览: 62
以下是Java代码实现:
```java
// Animal类
public class Animal {
protected String name;
protected String color;
protected int footNumber;
public Animal(String name, String color, int footNumber) {
this.name = name;
this.color = color;
this.footNumber = footNumber;
}
public void showInfo() {
System.out.println("Name: " + name);
System.out.println("Color: " + color);
System.out.println("Foot number: " + footNumber);
}
public void move() {
System.out.println("Move by flying, running, swimming, etc.");
}
}
// Bird类
public class Bird extends Animal {
public Bird(String name, String color, int footNumber) {
super(name, color, footNumber);
}
public void move() {
System.out.println("Move by flying");
}
public void nest() {
System.out.println("Build nest on the tree");
}
}
// Fish类
public class Fish extends Animal {
private int length;
public Fish(String name, String color, int footNumber, int length) {
super(name, color, footNumber);
this.length = length;
}
public void showInfo() {
super.showInfo();
System.out.println("Length: " + length);
}
public void move() {
System.out.println("Move by swimming");
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Animal animal = new Animal("Tiger", "Orange", 4);
animal.showInfo();
animal.move();
Bird bird = new Bird("Sparrow", "Brown", 2);
bird.showInfo();
bird.move();
bird.nest();
Fish fish = new Fish("Salmon", "Pink", 0, 30);
fish.showInfo();
fish.move();
}
}
```
输出结果如下:
```
Name: Tiger
Color: Orange
Foot number: 4
Move by flying, running, swimming, etc.
Name: Sparrow
Color: Brown
Foot number: 2
Move by flying
Build nest on the tree
Name: Salmon
Color: Pink
Foot number: 0
Length: 30
Move by swimming
```
阅读全文