Doubt on the utility of array polymorphism | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Doubt on the utility of array polymorphism

Is there any purpose in allowing a array to be referenced by its superclass? For a variable makes all sense, but a array? In which case would that be helpful? Does it only contribute to a possible ArrayStoreException? Example: public class Program {     public static void main (String [] args) {         Test [] arr = new Test_A [5];         arr [0] = new Test_B ();     } } class Test {} class Test_A extends Test {} class Test_B extends Test {}

8th Sep 2017, 3:24 AM
Rodrigo Temóteo
Rodrigo Temóteo - avatar
2 Answers
+ 5
Now you can have an array that contains all the sub-classes. An Example/ Animals[] world; // Lets say I have an array storing all the Animals in the world // This would have wolfs, snakes, people, elephants, etc.. for(int i = 0; i < world.length; i++) { Animal obj = world[i]; if(obj instanceof Snake) obj.hiss(); } Now only the Snakes have hissed! Even though we have an array holding every Animal. This makes sense because the array is supposed to contain every animal in the world. It would be a huge hassle to have an array for every different type of animal. edit: There could also be situations where we needed an array to have all the Animals (So making an array of all the different types of animals isn't even much of an option). Say, if we want to destroy the world by killing all of the animals. Itterate through the array and use their kill() method. All in all, an array of the super type can come in very handy.
8th Sep 2017, 3:31 AM
Rrestoring faith
Rrestoring faith - avatar
+ 2
I understood, but in case, this vector Animals [] world would at some point instantiated as new Animals [n] right? I can not see how useful it is for someone to make a new elephant [n], that is, instantiate an elephant vector and be referenced by an animal vector.
8th Sep 2017, 3:37 PM
Rodrigo Temóteo
Rodrigo Temóteo - avatar