public class Sentencegenerator {
private String[] subjects;
private String[] verbs;
private String[] directObjects;
public Sentencegenerator(){
subjects = {"Cat", "Dog", "Joe", "Teacher", "Policeman", "Doctor", "Dick"};
verbs = {"eats", "reads", "cums", "farts", "poops", "stabs", "cries"};
directObjects = {"book", "sticker", "fish", "man", "chiwawa", "marker", "cheese"};
}
public Sentencegenerator(String[] mySubjects, String[] myVerbs, String[] myDirectObjects){
subjects = mySubjects;
verbs = myVerbs;
directObjects = myDirectObjects;
}
我知道你只能在初始化数组时创建数组常量,但有没有办法可以创建一个数组实例变量,然后创建一个有自己常量的构造函数?
答案 0 :(得分:4)
有两种方法可以将数组实例化为常量数组:
String[] subjects = {"Cat", "Dog", "Joe", "Teacher", "Policeman", "Doctor", "Dick"};
或:
String[] subjects;
subjects = new String[] {"Cat", "Dog", "Joe", "Teacher", "Policeman", "Doctor", "Dick"};
在构造函数中,您需要使用后者(请注意new String[]
部分)。