| Author |
static nested class
|
sridhar row
Ranch Hand
Joined: Jan 16, 2008
Posts: 162
|
|
source: self Hi folks, I have a couple of questions from the above code i wrote. Can someone 1.tell me if there is any other way i can access outer class instance variable from inner class other than shown above. 2.explain line 2 and 3.in line 1 why am i not getting compiler error: non-static variable this cannot be referenced from a static context. Thanks
|
 |
Amit Ghorpade
Bartender
Joined: Jun 06, 2007
Posts: 2549
|
|
Hi,
I have a couple of questions from the above code i wrote. Can someone 1.tell me if there is any other way i can access outer class instance variable from inner class other than shown above. 2.explain line 2 and 3.in line 1 why am i not getting compiler error: non-static variable this cannot be referenced from a static context.
1. No there is no other way to access the outer class instance variable because the nested class is static 2. It is the proper way of instantiating a nested class. 3. It is because the nested class is static, and the member is an instance variable. Hope this helps
|
SCJP, SCWCD.
|Asking Good Questions|
|
 |
Dinesh Tahiliani
Ranch Hand
Joined: Aug 06, 2007
Posts: 486
|
|
|
Can you little elaborate...
|
Thanks<br />Dinesh
|
 |
Dinesh Tahiliani
Ranch Hand
Joined: Aug 06, 2007
Posts: 486
|
|
You can also access the instance variable of inner class without this.I have tried and code complies fine. output Outer class variable x: 10 Inner class variable y: 20 Can you please tell me why you have used this at line 2 in your code to access the 'y' varaiable of Inner class.
|
 |
sridhar row
Ranch Hand
Joined: Jan 16, 2008
Posts: 162
|
|
|
Thanks Amit for the reply. I know it is the correct way. What I'm asking is why is it the correct way and can you explain whats happening here: MyOuter.MyInner oi = new MyOuter.MyInner();<--explain this line.
|
 |
Amit Ghorpade
Bartender
Joined: Jun 06, 2007
Posts: 2549
|
|
MyOuter.MyInner oi = new MyOuter.MyInner();<--explain this line.
yes, here you are instantiating a static nested class. As you know, nested classes are simply members of the class like other members. say for example you need to access any static member of a class then you say ClassName.staticMember. similarly in above code you access the static nested class constructor. For inner classes, since thy are bound to instances, you need to say something like outerClassObj.MyInner() Hope this helps
|
 |
 |
|
|
subject: static nested class
|
|
|