Anonymous Class in Java

Anonymous classes can be tricky to understand for beginners.Mainly because the syntax can look verbose or at least it looked very confusing to me when I started my career as a java developer.So let’s talk anonymous classes today.

Anonymous classes were introduced in java to make code more concise and reduce the lines of code.Here’s some facts about anonymous classes

  • We can declare and instantiate an anonymous class at the same time.
  • They do not have a name.
  • An anonymous class have access to the members of its enclosing class.
  • An anonymous class can not access local variable in its enclosing scope that are not final or effectively final.
  • A variable declaration in an anonymous shadows any variable in its enclosing class with the same name
  • Can not declare static initialization blocks in anonymous classes.
  • Can not declare a constructor in anonymous classes

Example of anonymous class:-

Anonymous Class Example

When you run the program , you will get the following output:-

Syntax of Anonymous Classes:-

An anonymous class is an expression.It contains class definition inside the curly braces.

It has the following pieces:-

  • It starts with the new operator.
  • The name of the interface to implement or the class name.
  • Parenthesis that contain arguments to the constructor just the way we do it in a normal object instantiation.
  • A body of the anonymous class.The body starts and ends with curly braces and colon at the end of the ending braces

You can declare the following in anonymous classes:-

  • Extra Methods which are not originally declared in the interface or the class you are implementing
  • Initialization blocks
  • Fields
  • Local Classes

You can create an anonymous class from an interface or a class or an abstract class.

References :- Oracle Docs

That’s all about anonymous classes . I hope you enjoyed reading about anonymous classes.Have fun with coding.

Leave a comment

Your email address will not be published. Required fields are marked *