Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a superclass' constructor with new Array or ArrayList that contains data?

I am trying to call a superclass' constructor, with either an ArrayList(preferred) or array that already has information in it. I don't know what my syntactical mistake is, or if you can even do it?

I specifically want to insert "true" and "false" into either object. Just those two.

public class TrueFalseQuestion extends MultipleChoiceQuestion
{
    Answer myAnswer;
    StringPrompt myPrompt;

    //I can create, but not initialize data up here, correct?
    //Tried creating an ArrayList, but cannot insert the strings before calling constructor

    public TrueFalseQuestion()
    {
        /* Want to call parent constructor with "true" and "false" in array or ArrayList already*/
        super(new String["true", "false"]);
        ...
    }

I have a feeling this is a facepalm-er but I just cant figure it out. I've tried various ways, but the pain is the fact the super constructor MUST be called first, thus not giving me a chance to initialize the data.

like image 311
iaacp Avatar asked Nov 11 '12 21:11

iaacp


3 Answers

Use the format:

super(new String[] {"true", "false"});

if MultipleChoiceQuestion contains a constructor like this:

MultipleChoiceQuestion(String[] questionArray)

If it contains an overloaded constructor with a List argument as you say, for example:

MultipleChoiceQuestion(List<String> questionList)

then you can use:

super(Arrays.asList("true", "false"));

or if there a requirement for ArrayList to be used:

super(new ArrayList<String>(Arrays.asList(new String[] { "true", "false" })));
like image 147
Reimeus Avatar answered Oct 15 '22 04:10

Reimeus


If you have any control of the MultipleChoiceQuestion class you could change the constructor to this instead:

public MultipleChoiceQuestion(String ... values) {}

You'd then be able to call it like this:

public TrueFalseQuestion() {
    super("true", "false");
}

This is called varargs if you haven't heard about them before. You can read about it here: http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

like image 42
maba Avatar answered Oct 15 '22 05:10

maba


super(new String[]{"true", "false"});
like image 33
Juvanis Avatar answered Oct 15 '22 06:10

Juvanis