3

I have a problem. It stems from calling a subclass method from a superclass, but with a twist. Any insight would be greatly appreciated.

For example let's say I have a subclass MultipleChoice that extends an abstract superclass Question. The class MultipleChoice has a method addChoice(String choice), while Question does everything any question should do, like display the question prompt, and check for the correct answer.

I'd like to create an instance of MultipleChoice that references Question, and then call the addChoice(String choice) method. The reason for this is because I'd like to create a list of questions, and then put different types of questions in there (e.g. multiple choice, true and false, etc.).

Something like this:

ArrayList<Question> list = new ArrayList();
list.add(new MultipleChoice()); //this is valid
list.get(0).addChoice("abc");
list.get(0).addChoice("xyz"); //etc

However, this of course is a compile error, since not every question is a multiple choice type of question.

I know of two solutions for this.

  1. Typecast: ((MultipleChoice)list.get(0)).addChoice("abc");
  2. Add the method addChoice(String choice) into the superclass Question, so it can be overridden by MultiplceChoice.

Since I'm going to be accessing list many times, option 1 is well... ugly, while option 2 just seems to really poor practice, especially since Question is abstract.

How can I approach this elegantly?

1
  • This can be answered and solved in multiple ways. Can you perhaps add more background and maybe post the Question superclass and maybe other subclasses?
    – Keale
    Sep 27, 2014 at 6:56

2 Answers 2

3

There is nothing wrong with your second solution. Assuming the use of Java 1.5 or above, I would use generics. For example:

public abstract class Question<T>
{
  public void addChoice(T newChoice);
}

public class MultipleChoice extends Question<String>
{
  @Override
  public void addChoice(String newChoice)
  {
    // Do whatever you want here
  }
}

You could use Boolean for True/False questions.

As Keale suggested, you could also just add all the choices to the Question before you add the Question to the list. Have you considered perhaps using a constructor where you supply all the items up front?

Typecasting in the way you suggest for your first solution could eventually result in runtime errors if you attempt to cast something incorrectly. Say you have the following list of Question objects, by type:

MultipleChoice
MultipleChoice
Boolean
MultipleChoice
Question

When you loop over this list, you only know you have a list of Question objects. You have to check the type of each question before attempting to cast (using instanceof), or somehow keep track of which item in the list is of which type. Have a think about what will happen if you try to execute (MultipleChoice)list.get(2).

2
  • Good answer. Your answer is valid too. Goes to show how people think differently. :) IMHO however the addChoice method is only for the MultipleChoice. Other Question subclasses might have different answer types. This is difficult to decide without seeing the Question superclass and what it does exactly.
    – Keale
    Sep 27, 2014 at 6:55
  • 1
    @Keale - yes, I thought of that. The OP does not mention what the TrueFalse class does. If it has an initialisation-style method broadly equivalent to addChoice, this could be genericised in Question. If not, I agree with your response that it would be unwise to create such a method in Question if it only applies to MultipleChoice. Bottom line, anything relevant to all questions should be in Question - whether or not child classes need to override depends on the child class' required behaviour.
    – Flic
    Sep 27, 2014 at 7:03
2

It is not good practice to add a dummy method to the superclass that will only be used by one subclass. This will lead to confusion and misunderstanding if someone else (or you in the future) will work on the code and add a new type of question that will inherit from your superclass Question.

You can add objects to your list like so:

ArrayList<Question> list = new ArrayList<Question>();

MultipleChoice multipleChoiceQ1 = new MultipleChoice();
multipleChoiceQ1.addChoice("abc");

MultipleChoice multipleChoiceQ2 = new MultipleChoice();
multipleChoiceQ2.addChoice("xyz");

list.add(multipleChoiceQ1);
list.add(multipleChoiceQ2);

Using this method, you can add other Objects to the list that are subclasses of Questionlike so:

TrueAndFalse trueAndFalse1 = new TrueAndFalse();
//do something here

TrueAndFalse trueAndFalse2 = new TrueAndFalse();
//do something here

list.add(trueAndFalse1);
list.add(trueAndFalse2);

Then when accessing the list use instanceof to check for the data type. For example:

for (Question question : list) {
    if (question instanceof MultipleChoice) {
        MultipleChoice multipleChoice = (MultipleChoice) question;
        multipleChoice.doSomething();

    } else if (question instanceof TrueAndFalse) {
        TrueAndFalse trueAndFalse = (TrueAndFalse) question;
        trueAndFalse.doSomethingElse();

    }
}
1
  • Oh wow, I didn't think list.add(multipleChoiceQ1) would work where multipleChoiceQ1 is of type MultipleChoice. I don't know why I didn't try it that way. Now that I see it, it does seem intuitive. Thank you! Sep 27, 2014 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.