Java 从我创建的另一个类访问数组元素

标签 java arrays class methods static

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

Word attempts = new Word (26);

Word 类中的字段是

private String [] attempts;

Word 类中的构造函数是

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

其中 create 是一个使每个数组元素成为空字符串 ("") 的方法。在 Word 类中,我还有一个用于访问 attempts 数组的 getAttempts() 方法。现在,我想创建 Letter 类,在 for 循环中传递之前创建的数组 Word [] 。我尝试使用 Word.getAttempts()[i],但收到错误无法从 Word 类型对非静态方法 getAttempts() 进行静态引用。据我了解,当方法是静态的时,您不必在调用该方法之前创建对象。我不知道如何将 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()

...将是您访问 Word 类中名为 getAttempts 的静态方法的方式。但是,您的方法 getAttempts 不是静态的:它适用于您的类的实例。

假设您按如下方式定义这样的实例:

Word word = new Word(26);

然后,只要该方法是公共(public)的,您就可以通过以下方式访问该数组:

String[] attempts = word.getAttempts();

To my understanding when a method is static, you do not have to create an object before calling the method.

是的,但你的方法不是静态的。


I understand that, but after defining Word array in Main method, how can i access it in a new class?

您可以通过方法或构造函数传递对象,这允许其他对象使用公共(public)方法定义的 API 与其进行交互。

Now, I want to make class Letter where i pass the [...] array

定义一个名为 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(),但是您直接使用另一个类的内部值,这是不好的风格。通过其公共(public)方法比直接访问其私有(private)数据更好地使用 Word 实例。

关于Java 从我创建的另一个类访问数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48599379/

相关文章:

java - Libgdx 获取缩放的触摸位置

java - 当 JAR 没有包时 IntelliJ : How to use external JAR's as a library,

java - 什么是 ${project.licensePath}?

c - 如何使用数组汇总数据列表

C++ 类成员的循环引用

JavaScript - 在类方法内动态设置类属性

java - Java 调试中的回溯

javascript - 编写一个 javascript 乘法函数,它将返回两个单独的结果

c++ - 位掩码 : Set different states of an object via set method

c - 我正在尝试搜索文件计数。使用二分搜索遇到 ‘C’ 个保留字