Question

I am getting problems with these 2 lines. I need to create a class with an array of Animals using constants to size it. I have to fill the array Animal with Fish and Iterate in 2 different ways through the array executing move() and makeSound().

These are the lines:

1 animals[0] = new Fish()

2 for (Animal animal : animals) {

public class Animals {

    public static void main(String[] args) {
        final int SIZE = 6;
        Animal animal[] = new Animal[SIZE];
        animals[0] = new Fish()                // 1

        for (Animal animal : animals) {        // 2
            System.out.println("Bubbles");
            System.out.println("Swim");
        }
    }
}

My interface Animal:

public interface Animal {
        public void move();
        public void makeSound();
}

And my class Fish that implements Animal

public class Fish implements Animal{
@Override
    public void move() {
    System.out.println("Swim");
}

@Override
public void makeSound() {
    System.out.println("Bubbles");
}

private String color;
public String getColor(){
    return color;
}

public void setColor(String color){
    this.color = color;
    //Prefix this.color;
    }
}
Was it helpful?

Solution

A couple of syntax errors to fix:

  • Add a semicolon to the end of animals[0] = new Fish();
  • Change Animal animal[] = new Animal[SIZE]; to Animal[] animals = new Animal[SIZE];

Also, you should really be doing this in the for loop:

for(Animal animal : animals){
    animal.makeSound();
    animal.move();
   }

Just hard-coding print statements defeats the purpose of having the Animal interface, even if Fish is the only class implementing Animal at the moment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top