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
About Question enthuware.ocpjp.v7.2.1472 :
Moderator: admin
-
- Posts: 8
- Joined: Wed Mar 16, 2016 10:57 am
- Contact:
-
- Site Admin
- Posts: 10036
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1472 :
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.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,
-Paul.
If you like our products and services, please help us by posting your review here.
-
- Posts: 8
- Joined: Wed Mar 16, 2016 10:57 am
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1472 :
Ohhhh I'm running on Java 8.
Gotcha.
Thanks!
Gotcha.
Thanks!
Who is online
Users browsing this forum: No registered users and 38 guests