The smallest change to your code to do this job:
public String getSound() {
return Math.random() < .5 ? mySound : mySound2;
}
If you had a lot of sounds, I would use an array:
private String[] sounds = new String[10];
public String getSound() {
return sounds[new Random().nextInt(sounds.length)];
}
Note that mathematically 2 can be considered “a lot”: the version of the array can be used for 2 sounds.
varargs , :
punic class Animal {
private final String[] sounds;
public Animal(String type, String... sounds) {
this.sounds = sounds;
}
public String getSound() {
return sounds[new Random().nextInt(sounds.length)];
}
}