E
E
EvgenySManko2015-09-29 21:18:11
Java
EvgenySManko, 2015-09-29 21:18:11

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

2 answer(s)
E
Emin, 2015-09-29
@Ewintory

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;
   }
}

S
Sergey, 2015-09-29
Protko @Fesor

yes, you need to call the constructor, the construction
creates an array of references of the desired type. Roughly speaking,
equivalent

Curier crs = null, 
       crs2 = null;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question