I need to make several different class objects at runtime. This number is also determined at runtime.
Something like if we get int no_o_objects = 10 at runtime. Then I need to instantiate the class 10 times.Thanks
Read more about Arrays in the Java Tutorial .
class Spam { public static void main(String[] args) { int n = Integer.valueOf(args[0]); // Declare an array: Foo[] myArray; // Create an array: myArray = new Foo[n]; // Foo[0] through Foo[n - 1] are now references to Foo objects, initially null. // Populate the array: for (int i = 0; i < n; i++) { myArray[i] = new Foo(); } } }
Objects in Java are created only in Runtime .
Try the following:
Scanner im=new Scanner(System.in); int n=im.nextInt(); AnyObject s[]=new AnyObject[n]; for(int i=0;i<n;++i) { s[i]=new AnyObject(); // Create Object }
.
public AClass[] foo(int n){ AClass[] arr = new AClass[n]; for(int i=0; i<n; i++){ arr[i] = new AClass(); } return arr; }
List, .
List
MyClass[] classes = new MyClass[n];
n new MyClass() classes[i].
new MyClass()
classes[i]
This is a tricky question, and the perfect solution uses java reflection. You can create objects and throw them as needed at runtime. Also with this technology you can decide the number of instances of objects.
These are good links:
Reference1
Reference2
Source: https://habr.com/ru/post/1726211/More articles:Что это значит, когда в Mathematica синие слова выделены синим цветом? - wolfram-mathematicaA strange problem, Tomcat Webapp UTF-8 The character cannot be displayed correctly after every restart or every redistribution - tomcatHow can I extract HTML table data using Perl? - htmlUnable to bind compiled shaders (GLSL) - openglHow can I send a keyboard event to an application with the click of a button? - objective-cCreating an image from an array of colors on iphone - iphoneHow to wrap Commad executable in .app package? - user-interfaceRelative positioning + Absolute positioning VS Floats Left a Float Right (What approach do you use in your CSS)? - cssЧто такое хороший учебник или книга для изучения обработки кредитных карт с использованием PHP? - phpGet permission from an authorized attribute? - c #All Articles