我有抽象类“动物”和继承类“鱼和狗”。 我需要创建鱼和狗的各种物体,并给它们命名和品种,并制定它们移动方式的方法。 最后,我需要创建它们的数组,并随机打印4张,以显示它们的名称和品种。
主要类别:
public class JavaApplication38 {
public static void main(String[] args) {
Animal[] arr = new Animal[20];
arr[0] = new Fish("Riby", "Sea Fish");
arr[1] = new Dog("Any", "Great Dane");
arr[2] = new Fish("Ribytsa", "River fish");
arr[3] = new Dog("Jackie", "Pug");
arr[4] = new Fish("Bobi", "Mix");
arr[5] = new Dog("Ruby", "Labrador");
}
}
动物类
public abstract class Animal {
public Animal(String name, String breed){
}
public Animal(){
}
public abstract void moving();
}
狗类
Public class Dog extends Animal{
private String breed;
private String name;
public Dog(){
}
public Pas(String name, String breed){
this.name = name;
this.breed =breed;
}
@Override
public void moving() {
System.out.print("Walk\n");
}
}
鱼种
public class Fish extends Animal {
private String breed;
private String name;
public Fish(){
}
public Fish(String name, String breed){
this.name = name;
this.breed= breed;
}
@Override
public void moving(){
System.out.print("Swims\n");
}
}
问题是,我必须写什么循环才能通过数组打印名称和品种?
答案 0 :(得分:1)
问题是您在name
的每个子类中分别定义了breed
和Animal
。您需要在name
中创建breed
和Animal
实例变量。这样,Java知道每个动物都具有一个name
和breed
。
public abstract class Animal {
private String name;
private String breed;
public Animal(String name, String breed) {
this.name = name;
this.breed = breed;
}
public getName() { return name; }
public getBreed() { return breed; }
public abstract void moving();
}
public class Dog extends Animal {
public Dog(String name, String breed) {
super(name, breed);
}
@Override
public void moving(){
System.out.print("Walks\n");
}
}
public class Fish extends Animal {
public Fish(String name, String breed) {
super(name, breed);
}
@Override
public void moving(){
System.out.print("Swims\n");
}
}
现在,您可以为任何name
打印breed
和Animal
,无论是Dog
还是Fish
。
Animal[] arr = new Animal[6];
arr[0] = new Fish("Riby", "Sea Fish");
arr[1] = new Dog("Any", "Great Dane");
arr[2] = new Fish("Ribytsa", "River fish");
arr[3] = new Dog("Jackie", "Pug");
arr[4] = new Fish("Bobi", "Mix");
arr[5] = new Dog("Ruby", "Labrador");
for (Animal a : arr) {
System.out.println(a.getName() + " " + a.getBreed());
a.moving();
}