Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Some doubts abt Anonymous Inner Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Some doubts abt Anonymous Inner Class" Watch "Some doubts abt Anonymous Inner Class" New topic

Some doubts abt Anonymous Inner Class

Jeff Hu

Joined: Feb 03, 2005
Posts: 16
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?)


SCJP 1.4, SCJA 1.0
Jon Egan
Ranch Hand

Joined: Mar 24, 2004
Posts: 83
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

Joined: Mar 14, 2003
Posts: 812
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 ?

Thanks and Regards, Amit Taneja
I agree. Here's the link:
subject: Some doubts abt Anonymous Inner Class
It's not a secret anymore!