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");
    }
}
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • 1
    Related (if not duplicate): [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Slaw Jun 17 '21 at 03:55

2 Answers2

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();
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
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();
}
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183