Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static nested class question

 
Dirk Lehmann
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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"?


Regards
Dirk
 
anitha selvaraj
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
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
anitha
 
Dirk Lehmann
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Regards
Dirk
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Wayne,
thanks for you post and in fact this make sense...
Thanks and regards
Dirk
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic