I have a design problem:
- Question class: have a question and answer (String)
- TextQuestion class: normal text question and answer
- NumberQuestion class: question (String), answer (number – int, float…), and check answer using an epsilon value
But I have a problem with NumberQuestion. I must take the right answer, convert it into number, and compare to the answer from user. So how can I get the answer? Use getter method is not secure. Or my design is not good? How can I change?
public abstract class Question { private String question; private String answer; public Question(String question, String answer) { this.question = question; this.answer = answer; } public boolean checkAnswer(String yourAnswer) { // default implementation } } class TextQuestion extends Question { // Answer and Question is always string type, it's OK, not problem } class NumberQuestion extends Question { // Question is String, OK // Answer: input is number, accept approximately // Ex: Question: 1/3 = ? // Answer: 0.3 or 0.33 or 0.333 are accepted (using an Epsilon value) // so must override checkAnswer public boolean checkAnswer(String yourAnswer) { // HOW can I do? } }
I don’t see why you need to hide the answer from subclasses (or from any client code, for that matter). The client code surely needs to know the answer in the first place in order to create a
TextQuestionorNumberQuestioninstance.You should abstract away the logic of the test, as well as the answer type, from the
Questionclass: