Reputation: 11
I'm having an issue calling a class in the correct way. I have created a second class called "Questions" and I have created an instance of it under my main class like below:
Questions QuestionBank = new Questions ();
I expected to access all my variables from Questions
as QuestionBank.Score
, however when I do this QuestionBank
is highlighted in red. Questions.Score
works fine but doesn't match the instructions I have used.
Any thoughts?
Thank you in advance.
Upvotes: 0
Views: 46
Reputation: 3410
Questions.Score works fine
That is likely because you have declared your score static
public static int Score;
This means the Score
variable belongs to the Questions class itself and there is only one of it. No matter how many times you do new Questions()
to create a new instance, there will only be one Score
variable which belongs to the Questions
class and not instances of the Questions
class. This explains why you can only access Score
by Questions.Score
and not QuestionBank.Score
.
To solve this simply remove the static modifier.
public int Score;
Read up on What does the 'static' keyword do in a class?.
Upvotes: 2
Reputation: 1277
start with the look of java visibility
Let me say you will class like this
public class VariableAccessibility {
public static int STATICVARIABLE = 1;
public static final int STATICVARIABLECONSTANT = 1;
int protectedVariable = 1; //protected is default
public int publicVariable = 1;
private int privateVariable = 1;
public int getPrivateVariable() {
return privateVariable;
}
public void setPrivateVariable(int privateVariable) {
this.privateVariable = privateVariable;
}
}
Then you can / cannot to do following
VariableAccessibility varAccess = new VariableAccessibility();
int value = varAccess.publicVariable; //works because its public variable
int staticVariable = varAccess.STATICVARIABLE; //works
int consVar = varAccess.STATICVARIABLECONSTANT; //works, because its static
//int privateVar = varAccess.privateVariable; //not visible
int privateVar = varAccess.getPrivateVariable(); //works, call "getter" will be operating with private class variable
//static variables values modification VariableAccessibility.STATICVARIABLE = 5; //you can do, because static but not final //VariableAccessibility.STATICVARIABLECONSTANT = 5; //cannot to do, because its final
Basically, its a good point to have all what is possible marked as private
(with private modifier) and if needed, then create/generate getters and setters (methods with get / set in the name).
static and final are having special purpose:
Upvotes: 0
Reputation: 597
Since your question is pretty vague and difficult to understand, I feel this can be a very good understanding guide for you to understand.
Let me know of you have any problems. :)
Upvotes: 2