我的班级有以下代码,只有一个参数:
public class StudentChart {
public StudentChart(int[] Results) {
int[] results = Results;
}
如何在班级的其他地方使用结果?我假设在构造函数中声明的变量和数组是全局的,但显然不是。
另外,如果数据不是全局的,那么使用构造函数存储数据的目的是什么?
答案 0 :(得分:2)
您应该查看一些有关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.
答案 1 :(得分:1)
使它成为一个类变量。这样,当您调用构造函数时,您将填充结果数组并可以在类的其他位置使用它。您还希望此类变量是私有的。
public class StudentChart {
private int[] results;
public StudentChart(int[] Results) {
results = Results;
}
}