0

In Java , How can I declare an array of objects instanced from certain existing class ??

Java OOP , Array of objects

28th Jul 2021, 10:44 PM
Mohamed Mamdouh
Mohamed Mamdouh - avatar
1 Odpowiedź
+ 1
Pretty simple, this should be referenced in the Java course itself, and it would be more worthwhile to learn about it there. But I guess I should answer the question. Let's say we have the following empty class: public class MyClass{ MyClass(){ } } If we want to declare an array for containing objects of this class, we can use this statement: MyClass[] instances = new MyClass[number of elements to hold]; Now, we don't have any instances stored in the array yet, we only allocated space for an array of a given size of objects. To instantiate all of indices, we have to walk through it with a for loop. You can use a foreach or a for loop for this: for(MyClass ref: instances){ ref = new MyClass(); } or for(int i = 0; i < n; i++){ instances[i] = new MyClass(); } Unless I'm mistaken, the foreach method does work, as the retrieved element in the array is a reference to an object, and you set where it references to to the new instance. If anyone would care to correct me, feel free, as I'm not an expert when it comes to Java referencing.
29th Jul 2021, 12:10 AM
BootInk
BootInk - avatar