When you create an array in Java, all of the elements are nulls (for non-primitive types anyway; ints, for example will just be 0
). If you want to create an array with actual objects, you need to create them. One option (and the simplest) is to create them in a loop like this:
String dpt, salary, name;
Manager[] emp = new Manager[3];
for (int i=0; i<emp.length; i++)
{
emp[i] = new Manager(); // Create the object
name = JOptionPane.showInputDialog("Enter Name");
emp[i].setName(name);
}
Also notice that I use emp.length
in the for
loop instead of just the number 3. This is so that if the size of your manager array changes, you won't end up with ArrayIndexOutOfRangeException
(trying to access an element in the array that doesn't exist).
This question has a much more detailed answer that is definitely worth reading.