Java Riddle: Static Members in Inner Classes?
Here's something that can annoy the most experienced Java developers and is guaranteed to make people to mumble in job interviews (if that's your thing).
Consider the following piece of code:
On the face of it, the two variables are identical, but of a different type. So what's the problem here?
Hint 1: This will work with a String. It will not work with an int array.
Hint 2: This is the error you'll be getting (at least in Eclipse):
The field OBJECT_CONST cannot be declared static; static fields can only be declared in static or top level types
This hint is only more confusing. The error seems to apply to the integer field as well. So, what's the deal here?
If you know the answer, leave a comment.
- Login or register to post comments
- 9517 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)




Comments
Lemaire Raphael replied on Wed, 2008/07/23 - 6:51am
Wow, really confusing. I tried to use javac, and have a similar error whith the second constant :
Does someone have an explanation ?
Ian Pomanitskiy replied on Wed, 2008/07/23 - 7:03am
Arseniy Sizov replied on Wed, 2008/07/23 - 7:08am
Zviki Cohen replied on Wed, 2008/07/23 - 7:12am
Yes, that is correct.
It is confusing because many Java developers are not aware of the difference between a compile-time constant and a regular constant. Probably because Java has high abstraction level over the underlying compiler and machine.
Well done.
Lemaire Raphael replied on Wed, 2008/07/23 - 7:13am
Ok. This is logical, but lacks consistency, they could have disabled constants even for primitives to have the same behaviour for all types.
(Suppress primitives in java would be harder than I thought)
Aaron Digulla replied on Wed, 2008/07/23 - 9:31am
Osvaldo Doederlein replied on Wed, 2008/07/23 - 9:58am
Slava Imeshev replied on Wed, 2008/07/23 - 9:11pm
Guys,
you are missing the fact that the static block is executed during the class initialization, and you cannot initialize a non-static inner class without having an instance of the enclosing class. That's it.
Slava
Alen Vrecko replied on Wed, 2008/07/23 - 3:46pm
I'd never tought anybody would want to write code like that.
Let us not forget how one instantiates an inner class
new TestInnerStaticFinal().new MyInner();this might give a hint. An inner class can only live within an outer class, but if statics were allowed it could live outside the outer class which would defeat the purpuse of inner class at least this is how I see it.
Roger Crawfis replied on Sat, 2009/10/24 - 9:33pm