0

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?

2
  • 1
    Word for today is "field". Commented Nov 12, 2015 at 19:57
  • Can you post the entire class instead of just this snippet? Commented Nov 12, 2015 at 19:58

2 Answers 2

2

You should check out some articles on scope in Java.

Instance Variables

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; 

Argument Variables

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
}

Local Variables

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

Loop variables are only accessible inside of the loop body

while(condition){
        String foo = "Bar";
        .....
    }
    //foo cannot be accessed outside of loop body.
Sign up to request clarification or add additional context in comments.

Comments

1

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;
    }
}

2 Comments

You would want to make it final
I assume private would only allow method in the class to access it. Is this correct?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.