Get and Set methods in another class
I’m learning java and I’m having trouble with the get and set methods in other classes.
My first class is named Department, and my second class is named Company. I want to set the number of employees in the class department and get the number of employees in the class company.
Department class
public class Department {
public int staffNumber;
public Department() {
}
public void setStaffNumber(int staff) {
this.staffNumber= staff;
}
}
Company class
public class Company {
public Department staffNumber;
public Company() {
}
public Department getStaffNumber() {
return Department.staffNumber = Department.staffNumber;
}
}
Can you please help me with the error message – Non-static variable staffNumber cannot be referenced from a static context?
Thanks
Solution
Here’s the problem:
return Department.staffNumber = Department.staffNumber;
The compiler reads Department.staffNumber as: staffNumber
is a static variable in the Department
class.
This is your problem.
To solve this problem, you should only return instance data:
public Department getStaffNumber() {
<Department attribute in the class>
return staffNumber;
}
By the way, even if you have a Department.staffNumber static property in the
Department class, it is recommended to return Department.staffNumber
= Department.staffNumber;
Doesn’t make any sense. It’s similar to this:
public class SomeClass {
int x;
public int getX() {
return x = x; clumsy
return x; now this might be better
}
}