【问题标题】:Using Variables/Arrays from Constructor in Class在类中使用构造函数中的变量/数组
【发布时间】:2015-11-12 19:56:01
【问题描述】:

我的班级有以下代码,只有一个参数:

public class StudentChart {

public StudentChart(int[] Results) {

    int[] results = Results;
    }

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

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

【问题讨论】:

  • 今天的词是“字段”。
  • 你能发布整个课程而不仅仅是这个sn-p吗?

标签: java class variables constructor


【解决方案1】:

您应该查看一些关于 Java 范围的文章。

实例变量

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

 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.

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 你想把它做成最终的
    • 我假设 private 只允许类中的方法访问它。这是正确的吗?
    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 2020-10-18
    • 2013-06-20
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多