I agree, if you want to learn and test yourself to try to solve it without the computer first, but afterwards you can check if you were right by trying it out.
The last example should just compile normally. The argument variable hides the member variable. So inside the method, x refers to the argument variable, and not the member variable. If you want to access the member variable inside the method, you can prefix it with "this":
I just wanted to say thanks also! #6 was where my question was also. The bottom line I'm picking up here is that a static method's argument variable can "take" or "access" a non-static variable. Did I say that right? Thanks.
Matt Hanrahan wrote:... a static method's argument variable can "take" or "access" a non-static variable. Did I say that right? Thanks.
Not really... when you have a method with an argument that has the same name as a member variable, then inside the method, the argument is used instead of the member variable. So, the argument hides the member variable:
This doesn't really have anything to do with whether the method is static or not. A static method can never access non-static member variables.
Note: I made a mistake in my post above from 20 February. You can't use "this.x" in a static method, because "this" (the object that the method is being called on) doesn't exist in a static method.
Awesome and thank you. I was still not getting it exactly so I added a a main and tried to run the code.
I'm adding the two samples for anyone who has this same question as an example.
Let me know if I got anything wrong, but I think this helps to illustrate the point (which I think is an important one).
Will compile and output:
will not compile.
The compiler returns; "non-static variable x cannot be referenced from a static context"
Thanks again for the help!
Joined: Jan 28, 2007
The code on line five(5) works because, you are trying to print an argument variable which has scope and priority inside the method.
But the code on line 10 fails to compile because it is trying to use the variable on line 2 which is non static and hence cannot be referenced from the static context(main method).
Welcome to Java Ranch.
In class Foo3 if there was no final keyword then it would have compiled.
The final keyword states that the variable cannot be assigned any other value later.. Its like the gospel truth, cant change the variable value at all.
Now if you dont initialise the variable declared as final, JVM is surely going to cry foul play.
Hope this reasoning helps