Page 1 of 1

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

Posted: Mon Mar 19, 2018 3:01 pm
by TwistedLizard
Option 2:
Non-static inner classes cannot contain static members.

Commentary:
They can if the static variable is also made final.

Is this only for primitive member variables? Attempting to declare a final reference variable in a non-static inner class results in a compiler error, in this case at least:

Code: Select all

import java.util.Date;

class Test{
  class Inner{
    final static Date date = new Date();    //illegal static declaration
  }
  public static void main(String[] args){}
}

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

Posted: Mon Mar 19, 2018 10:47 pm
by admin
JLS Section 8.1.3 clearly states:
It is a compile-time error if an inner class declares a member that is explicitly or
implicitly static , unless the member is a constant variable (§4.12.4).
And as per 4.12.4,
A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28)
So for example, static final String s = ""; compiles but static final String s = new String(); doesn't.

That's explains why your code fails to compile.

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

Posted: Wed Mar 21, 2018 3:21 am
by TwistedLizard
ok. Thanks for your help.

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

Posted: Wed Apr 24, 2024 10:44 pm
by gadsgadsx
Hello, I think the explanation might be enhanced a little.

"This shows why an inner class cannot declare a static member, because the entire body of the inner class is in the scope of one or more enclosing instances.".

To me, all that comes before this statement have nothing to do with the explanation, what comes before is talking about static inner classes, and doesn't help to explain nothing about the case for non-static inner classes.

This design decision from Java bugs me every now and then, and I decided to dig deeper in this discussion. Recently I found that there's no real technical reason for this, and this was changed in JDK 16. So, there's a lot of people trying to justify this behaviour on the internet, and it's kinda confusing, because there's really no real reason.

Here's the issue that made the change in JDK 16: https://bugs.openjdk.org/browse/JDK-8254321

So, my suggestion would be to just enhance the explanation with a commentary regarding JDK 16+ and how that rule changed, even if this question is for JDK 11. This could help keeping things clear. Also, maybe the part that tries to justify the behaviour should be changed.

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

Posted: Thu Apr 25, 2024 2:29 am
by admin
Good point. Updated.
thank you for your feedback!