Over a million developers have joined DZone.

Static Members in Inner Classes? The Answer

DZone's Guide to

Static Members in Inner Classes? The Answer

· Java Zone
Free Resource

Managing a MongoDB deployment? Take a load off and live migrate to MongoDB Atlas, the official automated service, with little to no downtime.

I asked a question a few days ago, regarding static members in inner classes. I presented an example with two static members, one was integer the other Object type, the integer compiled correctly and the Object did not. Here's how it looks like in the IDE:

Java Riddle

The answer is found in the Java Language Specification 3rd Edition, Section 8.1.3:

Inner classes may not declare static members, unless they are compile-time constant fields

That's the answer. The integer is a compile-time constant which is in-lined by the compiler. The Object is not. Here are some more examples:


By the way, if the class was a static nested class, rather than an inner-class, there wouldn't be any problem defining static members. Plus, constants are inherited when using extensions. This means that the following is legit:


IMHO, Java is not a complex language. It is much simpler than C++, for sure. However, it does have some odd edges.

MongoDB Atlas is the easiest way to run the fastest-growing database for modern applications — no installation, setup, or configuration required. Easily live migrate an existing workload or start with 512MB of storage for free.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}