why can I declare A as static, and then access it without having to specify the class name in front of it ? I thought static variables in the class can only be referenced by putting the class name in front of it, not directly ? Please help me if I'm wrong ?
Second question: Why should B and C not also be static, if they're accessing a static variable ? (also using A)
Sorry, but STATIC just causes static in my brain. It makes no sense, even if I re-read the explanations.
(except that it's a variable that I can use in the parent class, and stays the same in there when I create new classes: that makes sense)
My task works, but I don't understand something ?
Resolved
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
4 March 2020, 14:49useful
A is defined in the same block of code as the main method (the Solution class block). This means the main method can access it without having to use its full qualified name (Solution.A). If you made another class (or block of code) inside this one, and had a static variable inside that, the main method would have to use the qualified name. Think of a block of code like a classroom full of students. If you said "John is a great person", and there was a John in the classroom, everyone would know who you were talking about. However if there was no John in the classroom people would ask "John who?", in which case you would have to use their full name so people knew which John you were talking about.
Here is a quick example:
In this bit of code you have 3 blocks of code:
1) lines 1-19, the Solution class block, which contains static int A, main() method, and test class
2) lines 4-14, the main method, nothing declared inside
3) lines 16-18, the test class, which contains static int B
The way the rules work, as simple as possible, anything inside a block of code where an object is declared can use just the variable name. Anything outside the block of code would have to use the qualified name.
I recommend looking into "Variable Scope" for more information. This is what this programming concept is called. +10
Johannes
5 March 2020, 07:03
Thanks, you rock
0