Java从我创建的另一个类访问数组元素
我正在使用main方法在类中创建一个数组Java从我创建的另一个类访问数组元素,java,arrays,class,methods,static,Java,Arrays,Class,Methods,Static,我正在使用main方法在类中创建一个数组 Word attempts = new Word (26); 类单词中的字段是 private String [] attempts; Word类中的构造函数是 public Word (int a){ attempts = new String [a]; create(attempts); } 其中create是一个方法,它使每个数组元素都成为空字符串(“”)。在Word类中,我还有一个getAttempt
Word attempts = new Word (26);
类单词中的字段是
private String [] attempts;
Word类中的构造函数是
public Word (int a){
attempts = new String [a];
create(attempts);
}
其中create是一个方法,它使每个数组元素都成为空字符串(“”)
。在Word类中,我还有一个getAttempts()
方法来访问attempts数组。现在,我想在for循环中传递之前创建的数组Word[]
的地方创建一个类字母。我尝试使用Word.getAttempts()[I],但遇到一个错误无法从Word
类型对非静态方法getAttempts()进行静态引用。根据我的理解,当方法是静态的时,在调用该方法之前不必创建对象。我不知道如何将Main方法中创建的数组传递给这个Letter类。有什么帮助吗
编辑:这是我的单词课
public class Word {
private String [] attempts;
public String[] getAttempts() {
return attempts;
}
public void create (String [] attempts){
for (int i=0; i<attempts.length; i++){
attempts[i]="";
}
}
public Word (int a){
attempts = new String [a];
create(attempts);
}
}
公共类单词{
私有字符串[]尝试;
公共字符串[]getAttempts(){
回击尝试;
}
创建公共void(字符串[]尝试次数){
对于(int i=0;i
…将是您在类Word
中访问名为getAttempts
的静态方法的方式。但是,您的方法getAttempts
不是静态的:它在类的实例上工作
假设您定义这样一个实例,如下所示:
Word word = new Word(26);
然后,如果方法是公共的,则可以通过以下方式访问阵列:
String[] attempts = word.getAttempts();
根据我的理解,当方法是静态的时,在调用该方法之前不必创建对象
是的,但是你的方法不是静态的
我理解这一点,但在Main方法中定义了单词数组之后,如何在新类中访问它呢
通过方法或构造函数传递对象,这些方法或构造函数允许其他对象使用公共方法定义的API与对象交互
现在,我想在通过[…]数组的地方创建类字母
定义一个名为Letter
的类和一个接受类Word
对象的构造函数
class Letter
{
private final Word word;
public Letter (Word word) {
this.word = word;
}
}
在主:
public static void main (String[] args)
{
Word word = new Word(26) ;
Letter letter = new Letter(word);
}
您可以直接传递word.getAttempts()
,但是您直接使用的是另一个类的内部值,这是不好的样式。通过其公共方法处理Word
的实例比直接访问其私有数据更好。消息说您的方法不是静态的……请插入您的class@Andr编辑了这篇文章,现在呢?我知道了理解这一点,但在Main方法中定义了单词数组之后,如何在新类中访问它呢?
public static void main (String[] args)
{
Word word = new Word(26) ;
Letter letter = new Letter(word);
}