0

I want to declare a new instance of a class, but have the name created from concatenation.

eg.

  for (int i = 0; i < 3; i++)
  {
     Class ('movement' + i) = new Class();

     switch(i) {

       case 0:
       movement0.stuff();
       break;

       case 1:
       movement1.stuff();
       break;

       case 2:
       movement2.stuff();
       break;
     }
  }

is this possible? I know this isn't the correct syntax, but it is me guessing

Adam Jarvis
  • 183
  • 1
  • 13
  • That's not declaring an instance, that's declaring a variable. – M A Nov 04 '15 at 19:27
  • Can't do that in java. – Maxqueue Nov 04 '15 at 19:29
  • What are you trying to achieve? maybe there's a Java way to do what you want. ie using polymorphism perhaps? – jb. Nov 04 '15 at 19:38
  • @jb I found this - http://stackoverflow.com/questions/16171941/how-to-generate-instance-name-dynamically I'm trying to dynamically create instances as the for loop iterates – Adam Jarvis Nov 04 '15 at 19:41
  • That's not a java feature. I think maybe php can do that? maybe? but its not a normal thing. Can you put stuff in a list? why do you want dynamically created instances? – jb. Nov 04 '15 at 19:45
  • @jb I could, it was just to try and make my code smarter. I wanted to have an object, then create new instances of said object as the for loop iterated – Adam Jarvis Nov 04 '15 at 20:04
  • clever != better :) Sometimes writing the cleverest code you can makes it really hard to read and figure out what is going on. In this case, even if you could do it, the code would be really hard to read since you don't know what type each object is. – jb. Nov 04 '15 at 21:24

0 Answers0