Anonymous Class in Java

Free Linux Book

Get FREE domain for 1st year and build your brand new site

We know that Java language mainly follows the OOPs concept (From Java 1.8, we get functional programming.). So there is no anonymous function in Java.
But we can create Anonymous objects by extending the concept of the inner class.

Anonymous Class


Topics that we will cover here:

What is Anonymous classes?

  • Java Anonymous inner class is an inner class without a name and for which only a single object is created.

  • It works just like the local class, all restrictions remain the same for its members.

  • You can declare the following inside an anonymous class.

    • Property (fields)
    • Methods (Only instance methods), even if they do not implement any methods of the supertype.
    • Instance initializer
    • Local classes

How to create Anonymous class?

Actually, in various works, we use anonymous classes. So there are many reasons to implement it.
Here we will look at an example of them.

// Step 1: Create an example class containing at least one member.
class A{
  public void show(){
   System.out.println("We are inside A class");
 }
}

// Step 2: Create the Main class which contains the main method.

public class Main{

  public static void main(String [] args){
  
  // Step 3: Create simple object and call the show() method
  A obj1 = new A();
  obj1.show();
  System.out.println("====================================");
  
  // Step 4: Create anonymous object
     A obj = new A(){
     
     @Override
     public void show(){
      
       System.out.println("Anonymous class has been created");
       
     } 
     }; //A semicolon is essential here.
  
  // Step 5 : Use your anonymous object.
  
    obj.show();
       
  }
}

Output

We are inside A class
====================================
Anonymous class has been created

Double Brace Initialization

Like a Senior Java Developer, if you want to create an anonymous class, Then learn a little about this weapon. Double brace initialization is a combination of two separate process in java. There are two { braces involved in it. If you see two consecutive curly braces { in java code, it is an usage of double brace initialization.First brace is creation of an anonymous inner class.Second brace is an initialization block. When you use the initialization block for an anonymous inner class it becomes java double brace initialization.

Let us see its implementation.

/*Here we will create a list in which the elements are 
stored with the help of double brace initialization.*/

import java.util.*;

public class Main{

public static void main(String[] args){

List <Integer> list = new ArrayList<>()
{{
 // Double Brace Initialization
 add(56);
 add(67);
 add(90);
 add(78);
 add(35);

}};

// print the list
System.out.println(list);
}
}

Output

[56, 67, 90, 78, 35]

When to use it?

Anonymous class is only created for one-time use, we cannot reuse it. Let us consider some scenario

  • When your only purpose is to override a method.
  • When you want to implement any functional interface. (We will see it with the help of real-world implementation).

Real World Implementation


Since, Anonymous class is created for one-time use only,It is mostly used for application development. For now, you can imagine any Android application.
Maybe we need to instantiate an interface to give functionality to a particular button of the UI. But we know that An interface can't be instantiated directly. In that case, Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time.

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity2 extends AppCompatActivity {

        private Button button;
        
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        
        button= findViewById(R.id.button_display);
        
        // set button funtionality in the  anonymous class
        button.setOnClickListener(new View.OnClickListener() {
        
            @Override
            public void onClick(View v) {
                
                /* this code will help you to display the particular message in the mobile screen.
                   whenever the button is clicked.
                 */
                Toast.makeText(MainActivity2.this,"Button is Clicked",Toast.LENGTH_LONG).show();
            }
        });
    }
}

Output
openiq_f.png

Questions


Q:)1

Can anonymous classes have static members in them?
No
Yes
Anonymous classes cannot have any static members except for those that are constant.

Q:)2

Can we access all the members of the outer class inside an anonymous class?
Yes
No
The reason is, of course, that an anonymous class holds an implicit reference to the enclosing class, and through that reference it can access any/all member fields & methods of the outer class.

With this article at OpenGenus, you must have the complete idea of Anonymous Class in Java.