Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static nested class

 
sridhar row
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2854
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you little elaborate...
 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2854
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic