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

How do I Read this?

 
Amit Batra
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
from the k&b
void makeBar() {
(new Bar(){}).go();
}
Is this is method local inner class or an anonymous class? If its anonymous how is it being declared inside a method? what exactly is going on here?
 
Neelesh Bodas
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adding some code around the fragment that you have given, to give it some contextual meaning



Observe that inside the makebar() method, we are creating an anonymous inner class, which is the subclass of class Sample. This inner class doesnot override any methods from the superclass. And then we just call the go() method on the newly created instance.
 
Douglas Chorpita
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The anonymous class is a subclass of the class Bar, not the class Sample.
 
Ramamoorthy Periasamy
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


class Bar might have declared as abstract to be more appropriate. Then only its a worth creating a anonymous class (which is a subclass of Bar).
 
Neelesh Bodas
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Douglas Chorpita:
The anonymous class is a subclass of the class Bar, not the class Sample.

Yes, True, Typo on my part. Thanks for pointing out.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic