7

My Background is C++ and in c++ we can easily create array of object using simple syntax. className obj[n]; and also constructor will call n time.

But When I tried to create array of object in java className[] obj=new className[n]; no constructor call. After searching I found the answer of this question on stackoverflow that it just create n Reference that can point to n objects and I need to create objects again for each reference like. obj[0]=new className();

Now I just want to ask why java do this? is there any reason even C++ allows but java not allows to create array of objects in same way? I searched for this but still didn't get exact answer.

Community
  • 1
  • 1

4 Answers4

9

In C++ you have flexibility to choose a memory in which you create the object. You can create objects in automatic area (on the stack), in the static area, or in the dynamic area. In the last case you get an object pointer, and become responsible for freeing it after you are done.

In contrast, all Java has is the dynamic area option, because all objects are reference objects. In C++ that would be equivalent to using objects only through pointers, and always creating them with new. When you do this in C++, you also have to fill your array of pointers with new-ed objects:

myclass *array[10];
for (int i = 0 ; i != 10 ; i++) {
    array[i] = new myclass();
}
...
for (int i = 0 ; i != 10 ; i++) {
    delete array[i];
}

Allowing creation of object arrays in C++ was a choice dictated by need to let programmers allocate arrays of objects in the automatic area. It came with a tradeoff, because objects from which you make arrays must have a default constructors. This is not ideal, because the requirement of default constructor sounds arbitrary.

Java, on the other hand, was free from the automatic memory requirement, so they went for a simple solution that requires you to initialize objects individually.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Not so often need you to create objects of the same type as array with default constructor. Sometimes you want to call the custom constructor. Sometimes you want to instantiate the subclasses and store them in the array.

Note that Java array className[] obj is more equivalent to C++ array className* obj[n], not just className obj[n], because it's an array of references to the objects, not the array of objects themselves. As of Java-8 you cannot create an array of objects themselves (they are discussed as part of project Valhalla, but will not appear even in Java-9). When the objects themselves are stored in the array in C++, you must initialize the array. You cannot keep "nulls" or something like this there, because null is not an object, it's the reference (or pointer). When you create className* obj[n] array in C++ (which is more similar to Java className[] obj array), it's uninitialized as well.

Finally note that in Java-8 you can quite easily create all the objects instantiating them with default constructor like this:

className[] array = Stream.generate(className::new).limit(n).toArray(className[]::new);
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • @Tiger if we need some time no-argu-constructor and sometime argu-constructor then why we create references? we can create object when we need different constructor.`className obj=new className(5);` or sometime `className obj2=new className("A");` As I expecting It could be just for code readability and less coding. Is there any other reason? (Sorry for poor English) –  Sep 20 '15 at 12:36
  • @Tagir Not your fault of course, but I wouldn't go as far as calling the Java-8 solution "easy" – Manos Nikolaidis Sep 20 '15 at 12:42
  • @LetDoit, sorry I don't understand your question. Try to rephrase it. If comment area is not enough, consider posting a new question adding all the necessary examples. – Tagir Valeev Sep 20 '15 at 12:44
  • @TagirValeev as your answer's first line, reference's array for different constructor but we can create different objects on our constructor requirement. then why we choose array of reference? –  Sep 20 '15 at 12:47
  • 1
    @LetDoit, you may want to create array like `className[] obj = {new className(0), new className(1), new className(2), new childClassName(3)};` initializing all the array elements in different way. But storing them in separate variables might be inappropriate if we want to process them uniformly after creation. – Tagir Valeev Sep 20 '15 at 12:49
  • @TagirValeev Thank You. –  Sep 20 '15 at 12:53
2

What is allowed or not do is up to the language designers.

If you want to initialize all elements of an Array with a reference to the same object in Java you can use :

className[] obj = new clasName[2];
Arrays.fill(obj, new className());

or to create different objects and pass different arguments to each constructor

className[] obj = new className[] {new className(), new className()};

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
  • then why we select different languages? there is reason that each language have difference of performance, security etc. and every language's designer select syntax/logic for a reason Sorry for poor english -_- –  Sep 20 '15 at 12:26
  • 1
    Note that `Arrays.fill` solution will create one object and assign it to every array element. Such result is rarely expected. Usually you need distinct objects for every array element. – Tagir Valeev Sep 20 '15 at 12:31
  • *"then why we select different languages? there is reason that each language have difference of performance"* ... often, the reason to select a language has nothing to do with performance. For example, you are working on a complex build system. It's multi-module and has many custom requirements. You end up choosing Gradle/Groovy because it is the right tool for the job ... and *certainly not* for its performance. – scottb Sep 20 '15 at 12:37
  • @LetDoit simplicity of syntax is not a strong point of Java. Far from it! Nevertheless, I am surprisingly more productive with Java compared to C++ because of the libraries that are available and the support I get from my IDE (Intellij) – Manos Nikolaidis Sep 20 '15 at 12:39
  • @scottb My comment's question was same as your answer. But it just due to poor English. Anyhow I got the reason. Thanks. –  Sep 20 '15 at 12:39
  • @ManosNikolaidis thanks and Sorry I forget to mention in Question that `I know the solution but not reason.` –  Sep 20 '15 at 12:40
1

In Java, whenever you declare a variable, be it a member of an object or a local variable, it's either of primitive type (byte, char, ...) or of reference-type (pointer to object of some type).
Thus, there are no arrays of objects, only arrays of references.

In C++ you have the freedom and responsibility to choose how many indirections you do, how to allocate, free, construct and destroy objects, adding much complexity:

  • dereference-operator (*pointer)
  • dereference-and-use-member (pointer->member)
  • address-of-operator (&object)
  • a way to derive a pointer-to-type from other types (type* var).
  • placement-new (`new(pointer) type(arg1, arg2);
  • explicit delete-operator (delete pointer)
  • much more.
Deduplicator
  • 44,692
  • 7
  • 66
  • 118