3

我正在学习 java,但我在其他类中的 get 和 set 方法有问题。

我的第一堂课叫部门,第二堂课叫公司。我想设置班级部门的员工人数并获取班级公司的员工人数。

部门班

public class Department {

    public int staffNumber;

    public Department() {
    }

    public void setStaffNumber(int staff) {
        this.staffNumber= staff;
    }

}

公司类

public class Company {

     public Department staffNumber;

     public Company() {
     }

     public Department getStaffNumber() {
          return Department.staffNumber = Department.staffNumber;
     }

}

您能帮我解决错误消息吗 - 无法从静态上下文中引用非静态变量 staffNumber 吗?谢谢

4

4 回答 4

3

问题在这里:

return Department.staffNumber = Department.staffNumber;

编译器将读取Department.staffNumber为:staffNumberDepartment类中的静态变量。有你的问题。

为了解决这个问题,您应该只返回实例数据:

public Department getStaffNumber() {
    //<Department attribute in the class>
    return staffNumber;
}

顺便说一句,即使你Department.staffNumber在类中有一个静态属性Department,建议的行return Department.staffNumber = Department.staffNumber;也没有任何意义。它类似于:

public class SomeClass {

    int x;

    public int getX() {
        //return x = x; //clumsy
        return x; //now this might be better
    }
}
于 2012-10-08T13:49:27.663 回答
0
     public Department getStaffNumber() {
          return Department.staffNumber = Department.staffNumber;
     }

Department.staffNumber 像静态变量一样被访问。应该是return staffNumber

你的吸气剂通常不会初始化。它应该只是返回

如果你想返回 Department 那么它应该是return staffNumber

如果你想返回 Department.staffNumber 它应该返回staffNumber.staffNumber将返回类型更改为int... 并修复变量名!

于 2012-10-08T13:50:16.577 回答
0

您正在尝试访问变量 staffNumber,因为它是一个静态变量

如果你想返回staffNumber,你应该返回staffNumber.staffNumber。不过,您使用的语义不好……您应该拥有:

public class Company {

     public Department m_department;

     public Company() {
         m_department=new Department();
     }

     public Department getStaffNumber() {
          return m_department.staffNumber;
     }

}
于 2012-10-08T13:51:06.897 回答
0

您似乎对基本概念感到困惑。请执行下列操作

public class Department {

    public int staffNumber;

    public Department() {
    }

    public void setStaffNumber(int staff) {
        this.staffNumber= staff;
    }

    public int getStaffNumber() {
        return staffNumber;
    }
}

现在StaffNumber在你的Company课堂上使用

public class Company {

    public Department dept;

    public Company() {
        dept= new Department();
    }

    public int getDepartmentStaffNumber() {
        return dept.getStaffNumber();
    }

    public void setDepartmentStaffNumber(int staff) {
        dept.setStaffNumber(staff)
    }
}
于 2012-10-08T13:54:42.553 回答