【问题标题】:Java access an array element from another class I createdJava 从我创建的另一个类访问数组元素
【发布时间】:2018-07-13 22:34:01
【问题描述】:

我正在使用 main 方法在类中创建一个数组

Word attempts = new Word (26);

Word 类中的字段是

private String [] attempts;

Word 类中的构造函数是

public Word (int a){
        attempts = new String [a];
        create(attempts);
    }

其中 create 是一种使每个数组元素成为空字符串 ("") 的方法。在 Word 类中,我还有一个 getAttempts() 方法来访问尝试数组。现在,我想在 for 循环中传递之前创建的数组 Word [] 来创建类 Letter。我尝试使用 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);
    }
}

总而言之,我正在使用 Word 类型的 Main 方法在类中创建一个数组,我想将该数组传递给单独的类 Letter。

【问题讨论】:

  • 消息说你的方法不是静态的......请插入你的类
  • @André 编辑了帖子,现在怎么样?

标签: java arrays class methods static


【解决方案1】:
Word.getAttempts()

... 将是您访问类Word 中名为getAttempts 的静态方法的方式。但是,您的方法 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;
    }
}

main:

public static void main (String[] args)
{
    Word word = new Word(26) ;
    Letter letter = new Letter(word);
}

你可以直接传递word.getAttempts(),但是你直接使用另一个类的内部值,这是不好的风格。通过其公共方法处理Word 实例比直接访问其私有数据更好。

【讨论】:

  • 我明白了,但是在Main方法中定义了Word数组后,如何在新类中访问它?
猜你喜欢
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
相关资源
最近更新 更多