gpt4 book ai didi

Java - 如何访问在 void 函数中创建的数组

转载 作者:行者123 更新时间:2023-12-01 13:34:22 25 4
gpt4 key购买 nike

感谢那些帮助我走到这一步的人。我做了一些改变。现在,在方法 Method() 中分配 array1 的行上出现错误。 (编辑后的版本如下所示)

公共(public)类JavaApplication2 {

int[] array1;
public JavaApplication2()
{
}

public static void main(String[] args) {
JavaApplication2 obj = new JavaApplication2();
obj.method();
System.out.print(obj.array1[1]);
}

public void method()
{
array1 = {1,1,1,1,1,1};
}

}

最佳答案

它们是在同一个类中定义的;然而它们是在方法内声明的,因此它们是局部变量。这意味着它们仅存在于各自的方法中,特别是仅存在于该方法的单次调用。本质上,它们会在方法退出时消失,并在每次调用该方法时重新创建。

引用the tutorial :

  • Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

您可能意味着它们是字段(也称为实例变量),这意味着类的每个实例化对象都有自己的“个人”变量,该变量与“拥有”它的对象一起持续存在。字段在类内部但在方法外部声明。

public class JavaApplication2 {
int[] array1; // variable declaration
// begins with the type of the variable

public JavaApplication2() {}

public void method() {
array1 = {1,1,1,1,1,1}; // assignment
} // begins with an identifier
}

通常,字段在构造函数期间初始化一次,因此您不必调用单独的方法来执行此操作。

public class JavaApplication2 {
int[] array1;

public JavaApplication2() {
array1 = {1,1,1,1,1,1};
}
}

关于Java - 如何访问在 void 函数中创建的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21390773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com