Reputation: 431
I have the following code for my class, with one parameter:
public class StudentChart {
public StudentChart(int[] Results) {
int[] results = Results;
}
How can I use results elsewhere in the class? I had assumed that variables and arrays declared in the constructor were global, but apparently not.
Also, what is the purpose of using the constructor to store data if it's not global?
Upvotes: 0
Views: 134
Reputation: 1400
You should check out some articles on scope in Java.
Variables defined within in a class itself and not in a constructor or method of the class.They are known as instance variables because every instance of the class (object) contains a copy of these variables. The scope of instance variables is determined by the access specifier that is applied to these variables.
public class StudentChart{
//instance variable private is the "access modifier" you can make it public, private protected etc.
private int[] results;
These are the variables that are defined in the header of constructor or a method. The scope of these variables is the method or constructor in which they are defined. The lifetime is limited to the time for which the method keeps executing. Once the method finishes execution, these variables are destroyed.
public int foo(int argumentVariable)
public class Foo{
public Foo(int constructorVariableArgument)
constructorVariable = constructorVariableArgument
}
A local variable is the one that is declared within a method or a constructor (not in the header). The scope and lifetime are limited to the method itself.
public void foo(){
int methodVariable = 0;
}
Loop variables are only accessible inside of the loop body
while(condition){
String foo = "Bar";
.....
}
//foo cannot be accessed outside of loop body.
Upvotes: 2
Reputation: 4638
Make it a class variable. This way, when you call the constructor, you will fill the results array and can use it elsewhere in your class. You'll also want this class variable to be private.
public class StudentChart {
private int[] results;
public StudentChart(int[] Results) {
results = Results;
}
}
Upvotes: 1