我正在使用 main 方法在类中创建一个数组
Word attempts = new Word (26);
Word 类中的字段是
private String [] attempts;
Word 类中的构造函数是
public Word (int a){
attempts = new String [a];
create(attempts);
}
其中 create 是一个使每个数组元素成为空字符串的方法("")
。在Word课堂上我也有一个getAttempts()
访问 attempts 数组的方法。现在,我想创建 Letter 类,其中传递之前创建的数组Word []
在 for 循环中。我尝试使用 Word.getAttempts()[i],但出现错误Cannot make a static reference to the non-static method getAttempts() from the type Word
。据我了解,当方法是静态的时,您不必在调用该方法之前创建对象。我不知道如何将 Main 方法中创建的数组传递给这个 Letter 类。有什么帮助吗?
编辑:这是我的Word类
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);
}
}
总而言之,我正在使用 Main 方法在类中创建一个 Word 类型的数组,并且我想将该数组传递给单独的 Letter 类。
Word.getAttempts()
...将是您访问名为的静态方法的方式getAttempts
在班上Word
。不过,你的方法getAttempts
不是静态的:它适用于您的类的实例。
假设您定义这样一个实例,如下所示:
Word word = new Word(26);
然后,如果该方法是公共的,您可以使用以下方式访问该数组:
String[] attempts = word.getAttempts();
据我了解,当方法是静态的时,您不必在调用该方法之前创建对象。
是的,但你的方法不是静态的。
我明白,但是在 Main 方法中定义 Word 数组后,如何在新类中访问它?
您可以通过方法或构造函数传递对象,这允许其他对象使用公共方法定义的 API 与其进行交互。
现在,我想在 Letter 类中传递 [...] 数组
定义一个名为Letter
,以及接受类对象的构造函数Word
.
class Letter
{
private final Word word;
public Letter (Word word) {
this.word = word;
}
}
And in main
:
public static void main (String[] args)
{
Word word = new Word(26) ;
Letter letter = new Letter(word);
}
可以直接通过word.getAttempts()
,但是你直接使用另一个类的内部值,这是不好的风格。更好地使用实例Word
通过其公共方法而不是直接访问其私有数据。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)