在类中使用构造函数中的变量/数组



我的类有以下代码,其中有一个参数:

public class StudentChart {
public StudentChart(int[] Results) {
    int[] results = Results;
    }

如何在课堂其他地方使用结果?我曾假设构造函数中声明的变量和数组是全局的,但显然不是。

此外,如果构造函数不是全局的,那么使用它来存储数据的目的是什么?

您应该看看Java中关于scope的一些文章。

实例变量

在类本身中而不是在类的构造函数或方法中定义的变量。它们被称为实例变量,因为类(对象)的每个实例都包含这些变量的副本。实例变量的范围由应用于这些变量的访问说明符决定。

 public class StudentChart{
    //instance variable private is the "access modifier" you can make it public, private protected etc.
        private int[] results; 

参数变量

这些是在构造函数或方法的头中定义的变量。这些变量的作用域是在其中定义它们的方法或构造函数。生存期限制为该方法持续执行的时间。一旦方法完成执行,这些变量就会被销毁。

public int foo(int argumentVariable)
public class Foo{
     public Foo(int constructorVariableArgument)
          constructorVariable = constructorVariableArgument
}

局部变量

局部变量是在方法或构造函数中声明的变量(不在头中)。范围和生存期仅限于方法本身。

public void foo(){
    int methodVariable = 0;
}

循环变量

循环变量只能在循环体内部访问

while(condition){
        String foo = "Bar";
        .....
    }
    //foo cannot be accessed outside of loop body.

将其设为类变量。这样,当您调用构造函数时,您将填充结果数组,并可以在类中的其他地方使用它。您还希望这个类变量是私有的。

public class StudentChart {
    private int[] results;
    public StudentChart(int[] Results) {
        results = Results;
    }
}

最新更新