3

Is there any special features in anonymous classes when compared to normal classes as I don't see anything special in those classes?

hata
  • 11,633
  • 6
  • 46
  • 69
  • Encapsulation and access would be my guess. Nothing else distinguishes them. – duffymo Sep 03 '15 at 13:39
  • Why we can't declare constructor in anonymous classes? – SanthoshPonraj Sep 03 '15 at 13:47
  • 2
    @Santhosh a Constructer method uses its Class name. For anonymous Classes don't have its names, they can't declair Constructor methods. – hata Sep 03 '15 at 13:55
  • 2
    @hata That's not a genuine reason, syntax can always be changed to do what we want. The real reason is a lot simpler: if you could define a constructor, how would you call it? A constructor only makes sense if you can explicitly create instances of a class, but the only way to instantiate an anonymous class is at the point of definition so there's simply no need for a constructor. – biziclop Sep 03 '15 at 14:42
  • @biziclop Thank you for your nice explanation :) – hata Sep 03 '15 at 14:45

2 Answers2

7

Is there any special features in anonymous classes when compared to normal classes

Indeed there is a special feature: they have the semantics of a closure which means you can access local variables in scope at their declaration site. Anonymous class is a special case of a local class which has the same feature; however a named local class is almost never used.

Compared to "normal" classes, anonymous classes are also inner classes, which means that they capture the instance of the enclosing class as well (if declared in a non-static context).

To summarize, anonymous classes are a union of all special features a Java class can have.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • `if declared in a non-static context`, this cannot be emphasized enough. 99% of anon inner classes I come across will unnecessarily capture an instance of an enclosing class. Most of the time it is harmless enough but every now and then... – biziclop Sep 03 '15 at 14:02
  • 3
    That's a bad aspect of the specification... they capture it unconditionally, even if it's never used in the implementation code. The spec could have been smarter about it (like the lambda spec _is_). – Marko Topolnik Sep 03 '15 at 14:04
0

Maybe programmer will be very tired, when must invent 100st mutation of XxxxxListener. Small snippets of code aren't worth. This is my personal opinion.

IMHO anonymous class is better than automatic generated names combo1, combo2, combo3 in IDE f.e. Delphi. Tired programmer accept such names for unimportant objects (local etc) but very important too, this is very bad habbit

Jacek Cz
  • 1,872
  • 1
  • 15
  • 22