Answer the question
In order to leave comments, you need to log in
Constructor in object array. How to implement?
Hello.
There is a class with a constructor. You need to create an array of objects by immediately calling the constructor. In other words: is it possible to call the constructor of each object when declaring an array?
Example:
class Main{
public static void main(String[] args)throws Exception{
int n = 5;
Curier[] crs = new Curier[n]; //Здесь же нужно вызвать конструктор
}
class Curier{
int p;
public Curier(int p){
this.p = p;
}
Answer the question
In order to leave comments, you need to log in
It is impossible, but what prevents to allocate a static method for this case?
class Curier{
....
public static Curier[] create(int size, int initialValue) {
Curier[] crs = new Curier[size];
for (int i=0 ; i<size ; i++)
crs[i]=new Curier(initialValue);
return crs;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question