0

Let's say I have an abstract class called 'Person' with three variables, them being: 'dateOfBirth', 'name', 'uniqueIdentifier' (social security number, etc).

dateOfBirth is LocalDate. name is String. uniqueIdentifier is String.

Then, I have another class called 'Dependent' that extends this class with a variable called 'kinship' as an enum called 'Kinship' which has the following values: 'Son', 'Nephew', and 'Other'.

However, in order to construct a Dependent, I need to check if his age is valid. He can't be older than 17 years old. I have an exception class ready and well and I am using this formula to check the validity for the construction:

if (Period.between(dateOfBrith, LocalDate.now()).getYears() > 17) {
    throw new DependentException("Dependent must be less than 18 years old!");
}

However, while doing this:

public Dependent(String name, String uniqueIdentifier, LocalDate dataOfBirth, Kinship kinship) {
        if (Period.between(dataOfBirth, LocalDate.now()).getYears() > 17) {
            throw new DependentException("Dependent must be less than 18 years old!");
        }
        else {
            super(name, uniqueIdentifier, dataOfBirth;
            this.kinship = kinship;
        }
    }

Eclipse refuses giving me the following error: Implicit super constructor Person() is undefined. Must explicitly invoke another constructor.

How would I go about fixing this error in order to prevent the Constructor from instantiating the object if it doesn't meet the logic requirements? Or am I supposed to do this outside the constructor? But, if I do this outside the constructor, how will my constructor know that there's a parameter to be followed? No rush, any help is appreciated! I'm a beginner and would like to understand what I'm doing wrong here.

Dark
  • 63
  • 1
  • 7
  • 4
    There is no need at all to prevent the super call. You can do that first and still throw an exception later in the constructor. – Tom Apr 26 '22 at 01:30
  • 1
    Note that the super statement should always be the first statement of the constructor of the subclass. – Scary Wombat Apr 26 '22 at 01:33

0 Answers0