I have two classes. The superclass:
public abstract class Question(){
public Question(String question, String answer, String... alts){...
}
And the subclass:
public class StringOptionsQuestion extends Question {
public StringOptionsQuestion(String question, String answer, String... alts){
if (alts.length == 0){throw new IllegalArgumentException();} //The compiler doesn't like this line.
super(question, answer, alts);
}}
I want my subclass, StringOptionsQuestion
, to validate the length of alts
before it passes it on to the superclass' constructor. However, I can't do it this way. I get the error "Constructor call must be the first statement in a constructor". Why does this error exist? And how can I bypass it in my case?
As kocko notes, the super
statement must be the first statement in your constructor. However, if you really, really don't want to get as far as the superconstructor before validating (e.g. because it will blow up with a less-helpful error), you can validate while evaluating the arguments to the superconstructor:
public class StringOptionsQuestion extends Question {
public StringOptionsQuestion(String question, String answer, String... alts) {
super(question, answer, validateAlternatives(alts));
}
private static String[] validateAlternatives(String[] alternatives) {
if (alternatives.length == 0) {
throw new IllegalArgumentException();
}
return alternatives;
}
}
See more on this question at Stackoverflow