Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't inner classes declare static members?

The Java Tutorial says that since an inner class is associated with an instance of the enclosing class, it (the inner class) cannot define any static members itself.

It's interesting for me why can't inner classes declare static members for instance, some private static field, which the instance of this inner class could possibly share with the other instances of the same inner class? is this just an implementation of things in Java that has to be taken for granted or something else?

like image 278
Dmitry Berdnikov Avatar asked Dec 18 '11 21:12

Dmitry Berdnikov


2 Answers

Basically just an arbitrary decision. there's no reason it couldn't be supported, but there is also not really any good reason to support it. just declare the static field in the outer class.

also, that quote may not be entirely correct: i believe you can declare a static serialVersionUID in an inner class.

like image 156
jtahlborn Avatar answered Sep 22 '22 23:09

jtahlborn


Because the Java Language Specification says so:

An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).

As for why it was specified that way, I do not know. My guess is that inner classes were designed as small helper classes that should be very limited in complexity.

like image 39
Michael Borgwardt Avatar answered Sep 18 '22 23:09

Michael Borgwardt