在另一个类中获取和设置方法

时间:2012-10-08 13:46:57

标签: java class methods setter getter

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

我的第一堂课名为Department,第二堂课名为Company。我想在班级设置一些员工,并获得班级公司的员工人数。

系类

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 个答案:

答案 0 :(得分:3)

问题在于:

return Department.staffNumber = Department.staffNumber;

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

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

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
    }
}

答案 1 :(得分:0)

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

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

你的getter通常不会初始化。它应该返回

如果您想返回部门,那么它应该是return staffNumber

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

答案 2 :(得分:0)

您正尝试访问变量staffNumber,因为它是static variable

如果要返回staffNumber,则应返回staffNumber.staffNumber。你正在使用糟糕的语义......你应该:

public class Company {

     public Department m_department;

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

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

}

答案 3 :(得分: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)
    }
}