所以我基本上应该使用从下面的Employee类创建的对象中的变量:
public class Employee {
public long EmployeeNumber;
public String EmployeeName;
public String LastName;
public double HoursWorked;
public double HourlyWage;
public Employee(long EmployeeNumber, String EmployeeName, String LastName, double HoursWorked, double HourlyWage ){
this.EmployeeNumber = EmployeeNumber;
this.EmployeeName = EmployeeName;
this.LastName = LastName;
this.HoursWorked = HoursWorked;
this.HourlyWage = HourlyWage;
}
public double getAnnualGrossSalary(){ // calculates annual gross salary
return HoursWorked*HourlyWage*52;
}
从我的主类创建了Employee对象,多个Employee对象存储在arrayList中。
现在我要做的是使用这些来自另一个类内的Employee对象的变量来计算税。
public double calculateTax() {
if (Employee.getAnnualGrossSalary() < 41495){
return Employee.getAnnualGrossSalary()*0.16;
}
else if (Employee.getAnnualGrossSalary() < 82985){
return Employee.getAnnualGrossSalary()*0.20;
}
else if(Employee.getAnnualGrossSalary() < 100970){
return Employee.getAnnualGrossSalary()*0.24;
}
else
return Employee.getAnnualGrossSalary()*0.2575;
}
我在另一个类中有一个为此写出的方法但是当我尝试使用它时,它一直说:
Cannot make a static reference to the non-static method getAnnualGrossSalary() from the type Employee
。
我该如何解决这个问题?
只是为了澄清,如果我把它设为静态,那么我的程序中没有任何其他功能可用,所以绝对没有办法让它静止。
答案 0 :(得分:4)
Employee
是类类型,它不是对象实例。如果方法getAnnualGrossSalary
是静态的,那么您可以使用Employee
。
您应该尝试将Employee
类的实例传递给方法:
public double calculateTax(Employee employee) {
if (employee.getAnnualGrossSalary() < 41495){
return employee.getAnnualGrossSalary()*0.16;
}
else if (employee.getAnnualGrossSalary() < 82985){
return employee.getAnnualGrossSalary()*0.20;
}
else if(employee.getAnnualGrossSalary() < 100970){
return employee.getAnnualGrossSalary()*0.24;
}
else
return employee.getAnnualGrossSalary()*0.2575;
}