• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Some doubts abt Anonymous Inner Class

 
Jeff Hu
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does it have constructor?

(I think it doesn't, because it doesn't have class name... but could you give me some more convincing reason?)

Thanks
 
Jon Egan
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, there's no constructor in the code, but there will be a default constructor, which is called when you instantiate the class, which is right when you're defining the class.

When you define an anonymous inner class, it's always "just in time": the class is defined right at the point when it is instantiated either to assign it to a reference variable or pass it to a method.

So the call usually looks like one of these:



In both cases you need an object which is a new type of (something)... either a new thing that implements an interface, or a new thing that extends a class. Notice the keyword new, and the parentheses after InterfaceType and SuperClassType - we're calling a constructor, it's just not one we define. It's the default, no-arg constructor, which calls the no-arg super() constructor as its only line.

I think of anonymous inner classes as working like normal classes, with the only exceptions being that they don't have a name, and don't exist until "just-in-time". If you wrote the above as "normal" classes, they wouldn't look too different:

 
amit taneja
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but what if super class has one defined constructor that takes one argument in that case we must invoke that constructor like

InterfaceType it = new InterfaceType(int) { public void methodFromInterface() { someImplementation(); }


and will compile if above code is present

is i m right ?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic