As the title suggests, I was wondering if there was a way to make my program execute the validation code in the constructor of my sub-class, instead of the validation code in the constructor in my parent class? Here is a very basic example:
Here I have the constructor of my Teacher class, which throws an exception if age < 18
Teacher(String name, int age) throws InvalidAgeException { this.name = name; this.age = age; if(age < 18){ throw new InvalidAgeException(); } } }
And here is the constructor & main method of my Student class, where I would like an exception to be thrown if age > 18, rather than throwing an Exception because age < 18.
Student(String name, int age) throws InvalidAgeException{ super(name, age); if(age > 18){ throw new InvalidAgeException(); } } public static void main (String[] args) throws InvalidAgeException { try { Teacher teacher = new Teacher("Matt Jones", 29); Student student = new Student ("Liam Price", 16); }catch(InvalidAgeException e){ System.out.println("Invalid age"); } } }
How could I re-write my code so that different validation checks can be carried out depending on the object being created? This is something I’ve found confusing in a few of my projects.
Thanks
Advertisement
Answer
Your code will check both validations in the sub-class, since you’re using the super() method. But having contradicting validations violates principles of good design, as a subclass be applicable anywhere the super class is applicable.
Instead of writing the validation in the constructor, it’s possible that you could write the validation as another method.