mon
mon

Reputation: 25

Access a Java object's variables from an object which is itself a variable of the target object?

I have written three Java classes:

Each Company object contains an array of Department objects, which in turn contain arrays of Employee objects.

I want to write a method in the Employee class setQid() which will set a unique ID for that employee in the following format:

Example:

My question is: how can I access the following variables from the context of my Employee class?

Please see my code below:

public class Company {

    private String name;
    private Department[] departments;

    public Company(String name, Department[] departments) {

        this.name = name;
        this.departments = departments;
    }
}


public class Department {

    private String name;
    private int number;
    private Employee[] members;

    public Department(String name, int number, Employee[] members) {

        this.name = name;
        this.number = number;
        this.members = members;
    }
}


public class Employee {

    private String firstname;
    private String surname;
    private String qid; //A unique employee ID

    public Employee(String firstname, String surname) {

        this.firstname = firstname;
        this.surname = surname;
        setQid();
    }

    public void setQid() {

        // How can I access the Company name, Department name, and Department number from here?
    }
}

Upvotes: 1

Views: 488

Answers (1)

Zohaib Ahmed
Zohaib Ahmed

Reputation: 211

You need to have a reference for the Department in your Employee class and a reference for the Company in your Department, only then will your relationships amongst your entities will be complete.

public class Company {

    private String name;
    private Department[] departments;

    public Company(String name, Department[] departments) {

        this.name = name;
        this.departments = departments;
    }
    //add getters and setters
}

public class Department {

    private String name;
    private int number;
    private Employee[] members;
    private Company company;

    public Department(String name, int number, Employee[] members) {

        this.name = name;
        this.number = number;
        this.members = members;
    }


    //add getters and setters
}

public class Employee {

    private String firstname;
    private String surname;
    private String qid; //A unique employee ID
    private Department department;

    public Employee(String firstname, String surname) {

        this.firstname = firstname;
        this.surname = surname;
        setQid();
    }

    public void setQid() {
     
      qid = department.getCompany().getName + "_" + department.getName() ....

    }

    //add getters and setters
}

Upvotes: 2

Related Questions