Java Anonymous Class With Examples

Java anonymous class are like local class or inner class without a name. We can use java anonymous class to declare and instantiate a class at the same time.

Java Anonymous Class

Java anonymous class is a nested or local class. You should use them only when you want to use local class only once. Let’s have a look at an example of anonymous class in java program.

Java Anonymous Class Example

Hello is an interface, let’s see how we can create an anonymous class implementation of Hello interface.

Above Hello class can be an abstract class also, like below.

Not only that, Hello can be a normal top level class also, like below.

Notice that anonymous classes are expressions and ends with semicolon.

Anonymous class is defined by calling class constructor followed by class definition code inside curly braces.

Since anonymous class don’t have a name, we can’t define a constructor inside the class code body.

Java Anonymous class example with constructor argument

What if our Hello class don’t have no-args constructor? Can we access class variables in the anonymous class? Do we need to override all the methods of class in anonymous class?

Let’s answer above questions with a simple code example.

Java Anonymous Class Important Points

  1. We can use any constructor while creating anonymous class. Notice the constructor argument is being used too.
  2. Anonymous class extends the top-level class and implements the abstract class or interface. So access modifier rules apply as usual. We are able to access protected variable, if we change it to private then we won’t be able to access it.
  3. Since we are extending the Hello class above, we are not required to override all the methods. However if it would have been an interface or abstract class then we have to provide implementation of all the unimplemented methods.
  4. You cannot declare static initializers or member interfaces in an anonymous class.
  5. An anonymous class can have static members provided that they are constant variables.

That’s all for anonymous class in java.

By admin

Leave a Reply

%d bloggers like this: