1

I am writing a code that has an ArrayList of the names of dogs. An interface method allows the animals to make sounds (ex. "woof"). I have a for loop that goes through the entire array and determines if the animal says. What I am having trouble with is that the obj.speak() is not working. Whenever I run it, it would say the symbol is not found but I am confused as I already put it there. I am not sure how to counter this issue as I went on serval websites to find answers but they were no help. I assume that the ArrayList is being looped over as I put a for-loop to go through the entire thing.

public class Main {
    public static void main(String[] args) {
        ArrayList dogs= new ArrayList();
        dogs.add(new Dog("Fred"));
        dogs.add(new Dog("Wanda"));
        for (Object e: dogs) {
            e.speak();
        }
    }
}
interface Speak{
    public void speak();
}
class Dog implements Speak {

    private String name;
    
    public Dog(String name) {
        this.name = name;
    }
    
    public void speak() {
        System.out.println("Woof");
    }
}
1

2 Answers 2

2

ArrayList can / should take a type

ArrayList<Dog> dogs= new ArrayList<>();
dogs.add(new Dog("Fred"));
dogs.add(new Dog("Wanda"));
for (Dog e: dogs)
{
    e.speak();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use generic type, not the raw type. Try to use the narrowest type possible (ex. Speak instead of Dog because you call only methods from that interface).

List<Speak> dogs = new ArrayList<>();
dogs.add(new Dog("Fred"));
dogs.add(new Dog("Wanda"));
for (Speak e: dogs) {
    e.speak();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.