my dog learned polymorphism*
The moose likes Java in General and the fly likes Static nested class question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Static nested class question" Watch "Static nested class question" New topic

Static nested class question

Dirk Lehmann

Joined: Aug 28, 2003
Posts: 7
Hi all,
can someone please explain me, why this does not compile...?
(I mean the marked line?)

Why doesn't the compiler resolve the instance "outer" to its class type "myOuter"?

anitha selvaraj

Joined: Nov 06, 2003
Posts: 2
All the member functions, varaibles, classes declared with static keyword, can be accessed directly by specifying the name of the class itself & need not be accessed thro' instance of the class.
i guess this is the reason,

with regds
Dirk Lehmann

Joined: Aug 28, 2003
Posts: 7
Hi Anitha,
yes I know that they can be accessed via their class name (myOuter)
or by one of their instances (outer).
The question is why in that case (myOuter=non-static, myInner=static) this does not work, and i have to use the class, while the reference via an instance causes a compiler error.
I mean why does the compiler tell me that

is a problem? As he should "resolve" this to
which works fine.
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
I don't claim to completely understand the ins and outs of inner classes, and I hope what I post won't add to the confusion.
Look at this code snippet:

Quoting from "Java in a Nutshell" regarding static member classes,

In code outside of the containing class, a static member class or interface is named by combining the name of the outer class with the name of the inner class.

So "myOuter.myInner.myConst" is well-formed and well-defined, but you should think of it as two components ["myOuter.myInner" as the class name/path, "myConst" as the static instance variable reference] as opposed to three components ["myOuter", "myInner" and "myConst"].
Within the "myOuter" class you can reference "myInner" w/out any qualifications, but outside of the "myOuter" class--as, for example, within the "myTest" class--the only way to refer to the inner class is to use "myOuter.myInner". So simply using "outer.myInner" has no meaning.
So in the code I posted I added:
myOuter.myInner inner = new myOuter.myInner();
which shows that you can refer to the "myInner" class, but you have to fully qualify it.
I hope this helps a bit ...
Dirk Lehmann

Joined: Aug 28, 2003
Posts: 7
Hi Wayne,
thanks for you post and in fact this make sense...
Thanks and regards
I agree. Here's the link:
subject: Static nested class question