Java实现程序本题要求在列表中存储动物,包括鸟和狗,请写代码完成下列内容: 1.定义抽象类Animal,包含私有属性name和age,为其完成setter、getter,带参构造方法,以及eclipse生成ToString方法 2.定义子类Bird继承Animal,完成带参构造方法,重写Tostring方法。 3.定义子类Dog继承Animal,添加属性leg,为其完成setter,getter,完成带参构造方法,重写ToString方法 4.在Main类的main方法中,定义列表list,在列
时间: 2023-09-30 18:12:16 浏览: 177
表中添加两个Bird对象和两个Dog对象,然后遍历列表,输出每个对象的信息。
代码如下:
Animal.java
```java
public abstract class Animal {
private String name;
private int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Animal [name=" + name + ", age=" + age + "]";
}
}
```
Bird.java
```java
public class Bird extends Animal {
public Bird(String name, int age) {
super(name, age);
}
@Override
public String toString() {
return "Bird [name=" + getName() + ", age=" + getAge() + "]";
}
}
```
Dog.java
```java
public class Dog extends Animal {
private int leg;
public Dog(String name, int age, int leg) {
super(name, age);
this.leg = leg;
}
public int getLeg() {
return leg;
}
public void setLeg(int leg) {
this.leg = leg;
}
@Override
public String toString() {
return "Dog [name=" + getName() + ", age=" + getAge() + ", leg=" + leg + "]";
}
}
```
Main.java
```java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Animal> list = new ArrayList<>();
Bird bird1 = new Bird("小鸟", 1);
Bird bird2 = new Bird("大鸟", 2);
Dog dog1 = new Dog("小狗", 1, 4);
Dog dog2 = new Dog("大狗", 2, 4);
list.add(bird1);
list.add(bird2);
list.add(dog1);
list.add(dog2);
for (Animal animal : list) {
System.out.println(animal.toString());
}
}
}
```
阅读全文