Inner classes belong to an instance of the enclosing class.
Mike said:
No, inner class *instances* have an enclosing *instance*.
So, for example, (untested)
public class Foo
{
class Bar
{
}
public static void main( String [] args )
{
Foo a;
Foo b;
}
}
In this example, a.Bar and b.Bar are /different/ classes. They cannot
share static non-constant members.
There's only one class; it's called Foo$Bar. Try running the following
program:
Interesting, because in the section (8.1.3) on inner classes the JLS
states
"So, for example, the class Local above has an enclosing instance of
class Outer. "
So while the actual implementation may use a single class definition, it
has to act as if each instance has its own Local class.
Since Foo$Bar is byte code, it is not a reliable indicator of what the
Java language is. That is why I went to the JLS for my insight.
The Java language is what's enforced by the compiler; Foo$Bar is what the
compiler produces after the syntax is approved, and is no longer Java.
Not only is Foo$Bar not associated with any instance, Foo$Bar isn't even
nested; it's implemented as a top-level class named Foo$Bar. Surely you
cannot conclude from this that there are no such things as nested classes
in Java.
But let's set aside what I said and talk about inner instances belonging
to outer instances. Define static, non-final X x inside Bar.
Assume Foo variables a and b reference different objects. a.x would belong
to a, and b.x would belong to b, by the rules of inner classes. But we
said x is static in Bar, so x does not belong to a or b. The
inner-classness wants the xes to be different but the staticness wants
them to be the same. I can imagine Gosling or whomever thinking that this
is tricky and weird, and somehow contrary to the notion of inner class
things belong to an outer class instance.
Besides, there is that little clause in the JLS that it would violate.
This isn't a defense of the syntax exactly. I am speculating on how it
makes sense to deny such static members given that they are denied, not
trying to say it's better than the alternatives.
So while it isn't maybe precisely true, although I think it is, that inner
classes belong to enclosing instances in Java, it sure is set up in the
language that you can think of it that way with impunity.
<
http://www.javaworld.com/javaworld/javatips/jw-javatip75.html>
"nested classes are associated with the enclosing class itself, whereas
inner classes are associated with an object of the enclosing class."