Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes Anonymous class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Anonymous class" Watch "Anonymous class" New topic

Anonymous class

satya sahu
Ranch Hand

Joined: Mar 26, 2003
Posts: 97
Can an anonymous class be declared as implementing an interface and extending a class?
The Answer is :An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

My question is why can't i declare both?
Ankit Garg

Joined: Aug 03, 2008
Posts: 9435

that's because the syntax of the Anonymous inner classes doesn't allow you to add an extends or implements clause

so you cannot write something like this

or like this

I think that's the reason....

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Stephen Davies
Ranch Hand

Joined: Jul 23, 2008
Posts: 352
This is perhaps a stab in the dark, but why would you want an anonymous inner class to extend or implement an interface? As an inner class can access members of its outer constituent class, why not extend the class or implement the interface(s) you reqire through the outer class to provide visibility for your inner class.

Just a thought

be a well encapsulated person, don't expose your privates, unless you public void getWife()!
Thyagarajan Ramanujam

Joined: Mar 24, 2008
Posts: 25
Anonymous class already a sub class.(ie) it already has a superclass. In java, a class cant have more than one super class.

For example,

Father son = new Father(){ };

the anonymous class extends Father class. So no further use of extend is possible.
Stephen Davies
Ranch Hand

Joined: Jul 23, 2008
Posts: 352
Thyagarajan: this an example of an anonymous inner class? Your example appears to be simply as a object reference to a Father type named son: Inner classes share more of an internal intimate relationship with their outer class, than an inheritance relationship(though it is indeed inheritance of sorts). I would assume, that inner classes anonymous and non, are a special sort of inheritance, where the outer (containing class) is the holding class rather than a superclass. Also due to the fact that, an instance of the outer class must be made to access the inner class by any sub-classes, suggests a specialized inheritance. I'm not very certain but, is it true that inner classes usually dont have constructors?

However, let me know if I am terribly wrong!
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 44616
Anonymous classes don't have written constructors; other inner classes can have them.
I agree. Here's the link:
subject: Anonymous class
jQuery in Action, 3rd edition