| Author |
Accessing static nested class with object of enclosing class
|
Cyril Sadasivan
Greenhorn
Joined: Jul 17, 2012
Posts: 20
|
|
The commented line of code doesn't compile.
I thought it should have because static members can be accessed through objects too.
Any justifications?
|
 |
Enkita mody
Ranch Hand
Joined: Aug 06, 2012
Posts: 333
|
|
|
I think you had forgotten correct syntax i.e new Demo.Nested().b;
|
OCA7
|
 |
Cyril Sadasivan
Greenhorn
Joined: Jul 17, 2012
Posts: 20
|
|
yeah that's right but the point is
if a static member variable can be accessed with object of enclosing class(objectOfEnclosingClass.staticVariable),
why can't static member class be accessed with object of enclosing class(objectOfEnclosingClass.staticNestedClass)?
|
 |
Enkita mody
Ranch Hand
Joined: Aug 06, 2012
Posts: 333
|
|
|
You shouldn't compare static class with static variables because it is really not.Static class is a Top level class, and Why can't you do that? because API doesn't allow that.We have to follow API.It won't work according to your desire.
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16692
|
|
Cyril Sadasivan wrote:
The commented line of code doesn't compile.
I thought it should have because static members can be accessed through objects too.
Any justifications?
I guess it can be argued that if the first is allowed, then the second should be allowed too -- considering other cases where it is similarly allowed.
The answer to this is likely defined somewhere in the JLS, but quite frankly, I was never a fan of using an instance to get to any static component, so never looked it up.... hence, I am leaving it as an exercise to the OP...
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
 |
|
|
subject: Accessing static nested class with object of enclosing class
|
|
|