I have an abstract superclass Employee and 2 subclasses Manager and Worker. I want to make a method in Employee that can add benefits – Managers can have benefits, Workers not.
I tried to do the following:
Employee has -> protected boolean rightsForBenefits;
Manager has -> final protected boolean rightsForBenefits = true;
Worker has -> final protected boolean rightsForBenefits = false;
Now in Employee I have this method
private void checkBenefitStatus() {
if(!rightsForBenefits) {
throw new RuntimeException("You are not allegeable to benefits");
}
}
public void addBenefit(String benefit) {
if(rightsForBenefits) {
...
}
But when I try to use this method, it always validates Employee.rightsForBenefit. How to point it to verify the rightsForBenefits of the subclasses?
>Solution :
Fields in java are not subject to polymorphism. The rightsForBenefits field in your Employee class will always refer to the field in the Employee class itself, not any subclass. you should use a method. not a field.
public abstract class Employee {
protected abstract boolean getRightsForBenefits();
private void checkBenefitStatus() {
if(!getRightsForBenefits()) {
throw new RuntimeException("You are not allegeable to benefits");
}
}
public void addBenefit(String benefit) {
checkBenefitStatus();
// add benefits logic
}
}
public class Manager extends Employee {
@Override
protected boolean getRightsForBenefits() {
return true;
}
}
public class Worker extends Employee {
@Override
protected boolean getRightsForBenefits() {
return false;
}
}