Search code examples
javaobjectmethodsincrementsetter

Setters on objects Java


Hello so I'm having a bit of difficulties with a setter method on objects.

public class Company {
    private  String companyName;
    public static int numberOfEmployees;
    public Employees employees[];

    public void setEmployees( String name, String heritage, String [] programmingLanguages, Salary d) {
      
        Employees employee1  = new Programmer(name, heritage,programmingLanguages, d,d.getBasicBrutoSalary());
        employees[numberOfEmployees] = employee1;
        numberOfEmployees++;

    }

So basicly this is a method defined in the 'company class' while making an Employees object who's using the parameters for making a 'Programmer'.

But that's not the deal, what I want tot do is by calling this setter method, automaticly create an object. So each time it's used, kind of increment the name of the object it's going to make.

So for example the first time I use it it makes an object called Employee1 and stores it in Employee[0].. second time I want it to store Employee2 into Employee[1].

Maybe I'm making this way too difficult but I'm just trying things out, and can't seem to find a way to make this work.


Solution

  • I suppose that Programmer object is subclass of Employees, or else it will not work. More or less it should look like the following:

    public class Company {
    private  String companyName;
    public static int numberOfEmployees;
    public static Employees employees[];
    
    public void setEmployees( String name, String heritage, String [] programmingLanguages, Salary d) {
        numberOfEmployees++;
        employees[numberOfEmployees] = new Programmer(name, heritage,programmingLanguages, d,d.getBasicBrutoSalary());;
    }