Hi all,
I am reading the topic
static and final in "Head First Java" book and there are these questions (the ones I did not get right) to find if the following code will compile or not:
Question 1:
My thought process: go is a non-static method (it can print the static variable x = 12, that should be okay) but wait..it takes a final int x as its argument (okay, now
this x variable is local to the go method, I should be careful in not changing this local variable inside
this method since it is marked "final"), tries to print variable x (
come on, now
is this the local variable or static variable, hmm..compiler should be confused...)..so my answer was
Compilation error..
I tried the code but the code ran fine {An instance f for Foo5 and f.go(5) prints 5}.
Question 2:
My thought process for this question: Instance variable x is 12. There is a static method go (so this gets initialized at Class initiation time and not per instance) and since the rule is static method can access only static variables, x is not known at Class initiation time ..so
(this time at least) is it
Compilation error?
Tried the code, wrong again. No compilation error {with f is an instance of Foo6, f.go(5) prints 5}.
Could someone please clarify these for me? Where am I going wrong or what am I missing?