Skip to main content

Anonymous inner class and its types with examples

anonymous inner class and types in java

What is Anonymous inner class?

When any inner class is defined without any name it is called as Anonymous inner class. Anonymous inner class also refer as name-less inner class.

From 4 categories of inner classes, Anonymous inner classes is most frequently used inner class in java.

Based on declaration and behavior there are 3 types of inner classes.

  1. Anonymous inner class that extends a class
  2. Anonymous inner class that implements interface
  3. Anonymous inner class that defined inside arguments

So lets see above three types in details with examples :

1. Anonymous inner class that extends a class

We can extends another class using anonymous inner class. like if we don't want to create class that extends another class all the time, then we can use anonymous inner class that extends a class.

Lets see simple example of both extending thread using another class and creating anonymous inner class that extends a class.

Example 1 : Extending Thread class using normal class

class MyThread extends Thread {
    
    public void run() {
        System.out.println("Child Thread");
    }
    
}

class Solution {
    
    public static void main(String[] args) {

        MyThread obj = new MyThread();
        obj.start();
    }
}

Example 2 : Extending Thread class using anonymous inner class

class AnonymousInnerClass {
    
    public static void main(String[] args) {

        Thread t = new Thread() {
            public void run() {
                System.out.println("Child Thread");
            }
        };
        t.start();
    }
}

In above example, if we do not create anonymous inner class then we have to create another class that extends Thread class.

Lets see another example how we can override method from anonymous inner class.

Example 3 : Override method from anonymous inner class.

class AnonymousInnerClass {
    
    public void methodOne() {
        System.out.println("methodOne");
    }
    
    public void methodTwo() {
        System.out.println("methodTwo");
    }
}

class Solution {
    
    public static void main(String[] args) {
       
        // Here we are using Anonymous Inner class, that extends a class (AnonymousInnerClass)
        // Creating Anonymous Inner Class and Overriding methodOne()
        AnonymousInnerClass obj = new AnonymousInnerClass() {
            public void methodOne() {
                System.out.println("Anonymous Inner Class : methodOne");
            }
        };
        
        obj.methodOne();
        obj.methodTwo();
        
        // For calling AnonymousInnerClass methodOne()
        AnonymousInnerClass obj1 = new AnonymousInnerClass();
        obj1.methodOne();
    }
}

Output :

Anonymous Inner Class : methodOne
methodTwo
methodOne

When we compile above code compiler generates 3 .class files :

  1. AnonymousInnerClass.class
  2. Solution.class
  3. Solution$1.class

2. Anonymous inner class that implements an interface

We can also implements interface using anonymous inner class. Lets see example of implements Runnable interface using inner class to create a Thread.

We will seen both normal implementation and inner class approach to implements Runnable interface.

Example 4 : Implements Runnable interface using normal class

class MyRunnable implements Runnable {
    
    public void run() {
        System.out.println("Inside run method");
    }
}
class Solution {
    
    public static void main(String[] args) {

        MyRunnable obj = new MyRunnable();
        Thread t = new Thread(obj);
        t.start();
    }
}

Example 5 : Implements Runnable interface using anonymous inner class

class MyRunnable {
    
    public static void main(String[] args) {

        Runnable r = new Runnable() {
            
            public void run() {
                System.out.println("Inside run method");
            }
        };
        Thread t = new Thread(r);
        t.start();
    }
}

Now lets see 3rd way to define anonymous inner class.

3. Anonymous inner class that defined inside arguments

We can also defined inner class inside method or constructor arguments. lets see example of that so you can understand easily.

Example 6 : Anonymous inner class that defined inside arguments

class ThreadDemo {
    
    public static void main(String[] args) {

        new Thread( new Runnable() {
           
            public void run() {
                System.out.println("Child thread");
            }
        }).start();
       
        System.out.println("Main thread");
    }
}

Points to remember for Anonymous inner class

  1. In normal class, we can implements any number of interface but in Anonymous inner class can implements only one interface at a time.
  2. In normal class, we can extends one class and implements many interface at same time but in Anonymous inner class can extends a class or can implements an interface but not simultaneously.
  3. In anonymous inner class we can not write any constructor explicitly. because name of class and name of constructor must be same but anonymous inner class does not have any name.

 

Happy Learning... Happy Coding..

Other articles :

 


Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...