简体   繁体   中英

An abstract method forced to be static in java

I'm not sure if the title is right but basically I have this piece of code:

for(int i = 0; i < ArrEmployee.size(); ++i){
        ArrEmployee.get(i);
        double provTax = ProvincialTax.calculateTax(ArrEmployee.get(i));

And this arrayList:

    List<Employee> ArrEmployee = new ArrayList<>(); //  array for employee objects

And the ProvincialTax class is like this:

public class ProvincialTax extends Deductions { // deductions is an abstract class with the abstract method calculateTax()

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;

}

}

So basically my arrayList ArrEmployee stores Employee objects that have the variables:

     public long EmployeeNumber;
     public String EmployeeName;
     public String LastName;
     public double HoursWorked;
     public double HourlyWage;

And the HoursWorked and HourlyWage are used to calculate AnnualGrossSalary used in my ProvincialTax class. With my for loop, I'm trying to calculate the provincial tax for each object inside the ArrEmployee , but it keeps asking me to make the method calculateTax() static, but it's supposed to override an abstract method?

How do I bypass this?

The problem isn't that you should make your method static, the problem is that you're invoking the method as if it was static, which you shouldn't do. The problem is in the line:

double provTax = ProvincialTax.calculateTax(ArrEmployee.get(i));

Which instance of ProvincialTax do you want to invoke it on? Invoke it on that instance.

ProvincialTax taxInstance = ...; // Get an instanceof of ProvincialTax
double provTax = taxInstance.calculateTax(ArrEmployee.get(i));

Without further evidence and the fact that you're not using preferred naming conventions, ProvincialTax.calculateTax appears to be trying to call the calculateTax via the ProvincialTax Class and not a instance of it...

ProvincialTax provincialTax = new ProvincialTax();
for(int i = 0; i < ArrEmployee.size(); ++i){
    double provTax = provincialTax.calculateTax(ArrEmployee.get(i));
}

You might like to have a read through Code Conventions for the Java TM Programming Language , it will make it easier for people to read your code and for you to read others

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM