Page 1 of 1

About Question enthuware.ocpjp.v7.2.1472 :

Posted: Wed Mar 30, 2016 9:07 am
by doziransky
Hi,

I'm a bit confused here.

I know method local variables are supposed to be accessible to classes defined within those methods only if those local variables are final, but then why does this work?

public class AccessTest {
static int x;
private String s;

void foo(String fooArg){
int count = 3;
class inner{
void fooInner(int k){
k = 0;
k = count;
System.out.println(k);
}
}
new inner().fooInner(0);
}

public static void main(String [] args){
new AccessTest().foo("hello");
}
}

Clearly I am able to access count and assign it to k.

Should I be interpreting accessible as able to be modified? Because I know if I try to assign to count then I'll get the error about it not being final.

But if I declare count as final then it can't be modified anyway.

Thanks

Re: About Question enthuware.ocpjp.v7.2.1472 :

Posted: Wed Mar 30, 2016 12:17 pm
by admin
doziransky wrote:Hi,

I'm a bit confused here.

I know method local variables are supposed to be accessible to classes defined within those methods only if those local variables are final,
or, from Java 8 onward, if they are "implicitly final" i.e. even if it is not declared final, if you don't change its value ever, then it is acting like a final and so the compiler treats it as final and allows the inner class to access it. You can't modify it of course because then it would not be implicitly final.

-Paul.

Re: About Question enthuware.ocpjp.v7.2.1472 :

Posted: Thu Mar 31, 2016 9:52 am
by doziransky
Ohhhh I'm running on Java 8.

Gotcha.

Thanks!