I've been allocating arrays using the following syntax while going through some Java tutorials so far:
// Ok, all the elements are zero upon creation
int[] a = new int[5];
// I can set all the elements however I want!
for (int i = 0; i < a.length; i++)
a[i] = i+1
But since when I started using a class, things have been confusing me:
class Employee
{
public Employee(String name, int age) {
emp_name = n;
emp_age = a;
}
void setName(String name) {
emp_name = name;
}
void setAge(int age) {
emp_age = age;
}
private String emp_name;
private String emp_age;
}
I use this class in the main function like the following:
Employee[] staff = new Employee[3];
This line should give me an array of three objects default initialized by the constructor as I assume.
When I do the following I get an exception on the runtime.
staff[0].setName("Test");
In C++, this has been be fairy simple which doesn't require an extra new
:
Employee *e[3];
So, upon further searching something tells me that I still need to allocate memory for each of the elements in array to actually start using them. If so, then what was the purpose of using new
operator? Doesn't it already allocate memory for the array? How come this doesn't happen with int
array?