Reputation: 7351
I find the new operator a bit confusing. My understanding now is that
new ClassName(...)
is to make an instance and call the Class' constructor. But what does new do when initiating an Array? For example, I feel the two new operators below are different, but can't explain clearly.
Employee[] staff = new Employee[3];
staff[0] = new Employee(...);
Are there any difference?
Thanks.
Upvotes: 1
Views: 545
Reputation: 5324
Employee[] staff = new Employee[3];
Is initializing your array of Employee
s with 3 "places" which can hold references to your Employee
objects.
That means it reserves 3 times the space needed for one object/instance of your Employee
class (e.g. 10byte) in the RAM (=> 30 byte).
But your array is initalized with "null".
While staff[0] = new Employee(...);
is creating a reference to your newly created object of type Employee
.
Upvotes: 3
Reputation: 83
When you call the class' constructor, an instance (object) of that class is created. The "new" keyword is what tells the compiler to create an object. An array is a class and you make objects of type Array of SomeClass. You need to use the keyword "new" because you are still creating an object.
Upvotes: 1
Reputation: 393866
new Employee[3]
creates an array that can hold references to 3 Employee instances. Each of them is initialized to null. staff[0] = new Employee(...);
creates an Employee
instance and assigns its reference to the first index of the array.
Upvotes: 4