繁体   English   中英

使用包含数据的新Array或ArrayList调用超类的构造函数?

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

我试图调用一个超类的构造函数,使用ArrayList(首选)或已经包含信息的数组。 我不知道我的语法错误是什么,或者你甚至可以做到这一点?

我特别想在任一对象中插入“true”和“false”。 就是那两个。

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"]);
        ...
    }

我有一种感觉,这是一个facepalm-er,但我无法弄明白。 我尝试了各种各样的方法,但痛苦的是超级构造函数必须首先被调用,因此没有给我机会初始化数据。

使用格式:

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

如果MultipleChoiceQuestion包含这样的构造函数:

MultipleChoiceQuestion(String[] questionArray)

如果它包含一个带有List参数的重载构造函数,例如:

MultipleChoiceQuestion(List<String> questionList)

然后你可以使用:

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

或者如果需要使用ArrayList

super(new ArrayList<String>(Arrays.asList(new String[] { "true", "false" })));

如果您对MultipleChoiceQuestion类有任何控制权,则可以将构造函数更改为:

public MultipleChoiceQuestion(String ... values) {}

然后你可以像这样调用它:

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

如果您之前没有听说过,这就叫做varargs。 你可以在这里阅读: http//docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

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

对于List (不是特定的ArrayList ),您可以这样做:

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

如果您需要特定的Arraylist<String> ,则需要执行以下操作:

super(new ArrayList<String>(Arrays.asList(new String[]{"true", "false"})));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM