Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.359 :

Posted: Wed Feb 22, 2012 1:04 pm
by ETS User
Hello,
the Explanation box for this question says : "Unlike popular belief and unlike mentioned in various books, anonymous class can never be static. Even if created in a static method."

If that were true, then it would be possible for the anonymous class to access a non-static member (such as an instance variable) declared inside the outer class, as in this code:

class A
{
}
public class TestClass
{
int outerInt = 7;
public class A
{
public void m() { }
}
class B extends A { }
public static void main(String args[]) {
new TestClass().new A() {
public void m() {
System.out.println("OuterInt is "+outerInt);
}
};
}
}

But this code won't compile because the compiler will detect an access of a non-static resource from a static context.
Perhaps didn't get the meaning of that explanation correctly; please shed some light on this. :cry:

Re: About Question com.enthuware.ets.scjp.v6.2.359 :

Posted: Wed Feb 22, 2012 1:56 pm
by admin
In this case, the inner class is unable to access outerInt, not because the inner class is static but because the inner class created in a static context (in this case a static method.)

There is not just one rule that applies while determining whether you can access a field or not. There are multiple rules that determine valid access.

An inner class can only access those fields that are available in its context. In this case, the main method is static and it doesn't have access to outerInt, so the inner class created in the main method also doesn't have access to outerInt.

This doesn't mean that the inner class itself is static.

HTH,
Paul.

Re: About Question com.enthuware.ets.scjp.v6.2.359 :

Posted: Fri Apr 21, 2017 5:07 am
by TwistedLizard
According to the commentary for option 3:
Anonymous classes are implicitly final.
Using reflection to test that, it doesn't seem to be the case, (assuming I'm testing what I think I am!)

Code: Select all

import java.lang.reflect.*;

class AnonymousTest{
  class A{}
  static void report(Object o){
    Class myClass = o.getClass();
    System.out.printf("%s\n", Modifier.toString(myClass.getModifiers()));
  }
  public static void main(String[] args){
    report((new AnonymousTest()).new A(){});   //static but not final
  }
}
although I don't think where would in practice be any way to extend the anonymous class.

Re: About Question com.enthuware.ets.scjp.v6.2.359 :

Posted: Fri Apr 21, 2017 5:48 am
by admin
But it is final as per the specification: https://docs.oracle.com/javase/specs/jl ... tml#15.9.5

Re: About Question com.enthuware.ets.scjp.v6.2.359 :

Posted: Fri Apr 21, 2017 5:53 am
by TwistedLizard
admin wrote:But it is final as per the specification: https://docs.oracle.com/javase/specs/jl ... tml#15.9.5
ok. Thank you.