• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Anonymous class

 
satya sahu
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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....
 
Stephen Davies
Ranch Hand
Posts: 352
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Thyagarajan Ramanujam
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 352
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thyagarajan:

..is 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
Sheriff
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anonymous classes don't have written constructors; other inner classes can have them.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic