0

I've run into an interesting problem wherein I am creating an array of objects with their values initialized in the constructors parameters, but the output (below in for loop) shows that the final element initialized will overwrite all other elements. I've hit a mental brick wall if anyone can help it would be greatly appreciated!

public class SoftwareServicesLtd 
{

public static void main(String[] args) 
{  
    Employee.employees[0] = new Employee("John", "Smalls", "Manager", "None", "None", 24000, "Human Resources");
    Employee.employees[1] = new Employee("Devin", "Nathan", "Manager", "None", "None", 24000, "Software Development");
    Employee.employees[2] = new Employee("Rhianna", "Mardsen", "HR Staff", "Devin", "None", 18000, "Human Resources");
    Employee.employees[3] = new Employee("Ryan", "Tepper", "Developer", "John", "C#", 20000, "Software Development");
    Employee.employees[4] = new Employee("Harry", "Wainwright", "Developer", "None", "Java", 15000, "Software Development");

    for(int i= 0; i < Employee.employees.length; i++)
    {
        System.out.println(i + "   -   " + Employee.employees[i].nameFirst_);
    }

Employee class and constructor:

public class Employee extends SoftwareServicesLtd {
    static String nameFirst_, nameLast_, employeeType_, skillSet_, department_ = " ";
    static String[] managers_ = new String[5]; 
    static double salary_ = 0;
    static Employee[] employees = new Employee[5];

public Employee(String first, String last, String employeeType, String manager, String skillSet, double salary, String department)
{
    nameFirst_ = first;
    nameLast_ = last;
    employeeType_ = employeeType;
    managers_[0] = manager;
    skillSet_ = skillSet;
    salary_ = salary;
    department_ = department;
}

Expected Output:

0   -   John
1   -   Devin
2   -   Rhianna
3   -   Ryan
4   -   Harry

Actual Output:

0   -   Harry
1   -   Harry
2   -   Harry
3   -   Harry
4   -   Harry
user3027864
  • 81
  • 1
  • 10
  • Expected and actual output? – Adrian Leonhard Mar 06 '15 at 00:25
  • You declared firstName as static, which means that there is only one variable for the whole class, which you set 5 times, instead of one variable per object. The compiler should be warning you that you are accessing a static variable with an object reference. `Employee.employees[i].nameFirst_`. Thats what it's warning you about. ;-) – Adrian Leonhard Mar 06 '15 at 00:26
  • Removing static gives the error 'non-static variable employees cannot be referenced from a static context' @Sotirios But as far as I can see I'm not? – user3027864 Mar 06 '15 at 00:39
  • Do a search for that error message. – Sotirios Delimanolis Mar 06 '15 at 00:40

0 Answers0