0

Naming using dynamic variables

I'm trying to create a new instance of a class, by naming each variable dynamically. For example I want to create a new instance of my tiger class each time the uses asks to get a new tiger, however in this line of code: Tiger (Variable name) = new Tiger; I want the variable name to be like t1, t2, t3. Does anyone have any idea how to do this or if its possible? I have String tig = "t" + animalcount; working which can create the right strings (t1,t2,t3,t4 etc) but I don't know how to turn this into a variable name for the bit above. Any help appreciated or how I could get around this another way, thank you!

24th May 2020, 7:15 PM
Kiera Bennett
Kiera Bennett - avatar
1 ответ
0
I guess not possible but you can use Array of objects.. public class Program { public static void main(String[] args) { Object []s=new Object[10]; for(int i=0; i<10; i++){ s[i]=new Program(); System.out.println(s[i]); } } } Hope it helps you get an idea..
24th May 2020, 7:25 PM
Jayakrishna 🇮🇳