Working with Java Anonymous Class

Java Anonymous Class

Anonymous Inner Class are classes in java that have no name. It is mostly used when a local class is mostly needed to be used once.

However, Anonymous Inner Class just like normal class, can extend other classes but cannot extend a class and implement an Interface at the same time.

it can have access to local variables within the method or class it was declared. But other classes or methods can’t have access to it.

Some rules and other things involved in declaring an Anonymous class
1. Contructors are not declared inside Anonymous class.
1. Many methods can be declared inside an anonymous class

Look at the AnonymousInnerClassDemo below for more understanding. 

public class AnonymousInnerClassDemo {
     public static void main(String… args) {
        AnonymousInnerClassDemo anonymous =
            new AnonymousInnerClassDemo();

     //declaring an interface
  interface Logo {
        public void myLogo();
        public void churchLogo();

      //this is a method inside the AnonymousInnerClassDemo Class
      public void siteLogo() {
          //this is an inner class inside method implementing the interface Logo
       class Graphics implements Logo {
            int width = 300;
            int height = 200;

            public void myLogo() {
                System.out.println(“The Width of the Logo is: ” + width);
            public void churchLogo() {
                System.out.println(“The height of the Church Logo is: “+height+”n”);
      //calling the inner class Graphics
        Logo lg = new Graphics();
        //Declaring the Anonymous inner class
        Logo otherDesign = new Logo() {
            public void myLogo() {
                System.out.println(“Other Design can be here”);
            public void churchLogo() {
            System.out.println(“TOther Church Logo design can be here”);
        //calling the Anonymous Inner Class
        //There can be many methods inside the anonyous inner class

Be the first to comment

Leave a Reply

Your email address will not be published.