public class TestClass
{
static int si = 10; int ii = 20;
public static void inner()
{
int ai = 30; //automatic variable
final int fai = 40; //automatic final variable
class Inner
{
public Inner() { System.out.println(si+" "+fai+" "+ai);
}
}
new Inner();
}
public static void main(String[] args) { TestClass.inner(); }
}
The explanation tells me that "ai" can't be acessed. But when I tested it Inner class was able to access ai.
Can you please elaborate why you have mentioned "ai can't be accessed"?
about enthuware.ocpjp.v7.2.1480
Moderator: admin
-
- Posts: 1
- Joined: Wed Jun 07, 2017 5:21 am
- Contact:
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: about enthuware.ocpjp.v7.2.1480
This is because of a change between Java 7 and Java 8. The rule is that an inner class is only allowed to access final variables of the encompassing method.
Although ai is not declared final, its value is never changed anywhere in the code. Therefore, this is called an "implicitly" final and while Java 7 does not allow such variables to be accessed in the inner class, Java 8 does.
So, you are probably using Java 8 compiler. If you try to compile the code using Java 7, it will not compile.
Please note that this question belongs to the OCPJP7 question bank and you should use Java 7 compiler to study for OCPJP 7 ( i.e. 1Z0-804) exam.
If you are studying for OCPJP 8 (i.e 1z0-809), you should not use this question bank.
HTH,
Paul.
Although ai is not declared final, its value is never changed anywhere in the code. Therefore, this is called an "implicitly" final and while Java 7 does not allow such variables to be accessed in the inner class, Java 8 does.
So, you are probably using Java 8 compiler. If you try to compile the code using Java 7, it will not compile.
Please note that this question belongs to the OCPJP7 question bank and you should use Java 7 compiler to study for OCPJP 7 ( i.e. 1Z0-804) exam.
If you are studying for OCPJP 8 (i.e 1z0-809), you should not use this question bank.
HTH,
Paul.
Who is online
Users browsing this forum: No registered users and 10 guests