About Question enthuware.ocpjp.v7.2.1472 :

Moderator: admin

Post Reply
doziransky
Posts: 8
Joined: Wed Mar 16, 2016 10:57 am
Contact:

About Question enthuware.ocpjp.v7.2.1472 :

Post by doziransky » Wed Mar 30, 2016 9:07 am

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

admin
Site Admin
Posts: 8702
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post by admin » Wed Mar 30, 2016 12:17 pm

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.
If you like our products and services, please help us by posting your review here.

doziransky
Posts: 8
Joined: Wed Mar 16, 2016 10:57 am
Contact:

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

Post by doziransky » Thu Mar 31, 2016 9:52 am

Ohhhh I'm running on Java 8.

Gotcha.

Thanks!

Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest