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!
If I understand the problem correctly, then the simplest fix would be to not declare another
soundsvariable inPirateParrot. Instead, make suresoundsis declaredprotectedinParrot, and then in thePirateParrotconstructor just populate the inheritedsoundsvariable with whatever sounds you want thePirateParrotto have.Another alternative might be to have a
getSounds()method that returns the list and callgetSounds()from inside ofspeak()instead of referencingsoundsdirectly. ThenPirateParrotwould just need to overridegetSounds()to return its version ofsounds.