我不太确定这是如何工作的,但是如果我想选择为类的对象提供更多或更少的变量,这是否适用于这样的多个构造函数?
假设我想创建一个多项选择题,但是我不知道我的用户想输入多少个答案,也许是 2,3,4,5,6?所以为此:
public class Quiz {
private int counter;
private String question;
private String answer1;
private String answer2;
private String answer3;
private String answer4;
private String answer5;
private String answer6;
private String rightAnswer;
public Quiz(int counter,String question, String answer1, String answer2, String rightAnswer){
super();
this.counter = counter;
this.question = question;
this.answer1 = answer1;
this.answer2 = answer2;
this.rightAnswer = rightAnswer;
}
public Quiz(int counter, String question, String answer1, String answer2, String answer3, String rightAnswer) {
super();
this.counter = counter;
this.question = question;
this.answer1 = answer1;
this.answer2 = answer2;
this.answer3 = answer3;
this.rightAnswer = rightAnswer;
}
public Quiz(int counter, String question, String answer1, String answer2, String answer3, String answer4,
String rightAnswer) {
super();
this.counter = counter;
this.question = question;
this.answer1 = answer1;
this.answer2 = answer2;
this.answer3 = answer3;
this.answer4 = answer4;
this.rightAnswer = rightAnswer;
}
//...more options
也许我可以用某种枚举或开关做 1 个构造函数?归根结底,在尝试了这种方法之后,出于某种原因,将其放入哈希映射中,然后将其序列化到文件中不起作用,与 1 构造函数一样,它可以工作,但不会在其中写入所有内容。我对问题是什么感到有些困惑,也许这与我的 toString 覆盖有关,但无论如何,请告诉我这个问题,这样我就不必担心一个不那么令人困惑的问题了。