I have a question about the use of data structures such as ArrayLists in a simple inheritance structure. I'm having a difficult time wording it: hopefully you can understand what I am trying to ask.
I have a Superclass Parrot and a Subclass PirateParrot extending Parrot. In Parrot, I have the following method:
public String speak() {
int rand = (int)(Math.random() * sounds.size());
return sounds.get(rand);
}
Which returns a random string in an ArrayList called sounds which is created in the Parrot class.
If I create a separate instance of PirateParrot called polly, which also has its own ArrayList, and try to call polly.speak(); without any implicit implementation for the speak method in the PirateParrot class, I get thrown an "Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0"
If I specifically copy/paste in the speak() method from Parrot into PirateParrot, the code compiles fine and runs properly. What exactly was the problem previously? Is there a way to make this run correctly without having to copy/paste the speak() method into PirateParrot? Thanks!
Random.nextInt(sounds.size()), which would also have the side effect of throwing an exception whensoundsis empty -- which appears to be what's happening.