Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Anonymous inner classes  RSS feed

 
Siva kandasamy
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,
See the code below. Can you please explain the meaning of the stmt #9 and why I am unable to print as I was trying to do at line # 12.
thanks
siva
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Line 9 is creating an instance of an anonymous inner class that is a subclass of Outer. It's called an anonymous inner class because it doesn't have a name. At least it doesn't have a name in your code - the compiler does actually give it a name, but it's not a name that you, the programmer, are intended to make use of.
Although, this instance of the anonymous inner class is defined to have an instance member named j, this member isn't actually accessible outside of this anonymous inner class definition (if we ignore reflection). The reference variable that refers to the instance of this anonymous inner class is of type Outer - the parent class. Things of type Outer don't have a member named j and so things of type Outer cannot access a member named j. As far as the compiler is concerned, it is only certain that the reference o is of type Outer, and things of type Outer don't have a member named j, and so the compiler won't let you reference a member named j. That's why the commented out line 12 won't work.
Making sense?
Note that this code makes use of Polymorphism. If that's a new or not-yet-comfortable topic for you, then I'd suggest a quick read of the "How my Dog learned Polymorphism" article in the JavaRanch Campfire Stories.
[ January 02, 2004: Message edited by: Dirk Schreckmann ]
 
Siva kandasamy
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dirk,
Thank you for your posting. It makes sense.
I would appreciate, if you let me know, how do I access variable j from my example.
thanks
siva
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you gave the anonymous inner class definition a name, so that it were no longer anonymous, then you could create a variable of the proper type to access that member. Otherwise, excepting something advanced with reflection, you can't.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!