Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to have a method in superclass that validates a field in the subclass

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading