Home core java Java anonymous class with examples

Java anonymous class with examples

1. Java anonymous class

Sometimes we can declare inner class without name such type of inner class are called anonymous class. Java anonymous class is a inner class with no name.

The main objective of anonymous inner classes is “just for instant use”.
We may use java anonymous classe 3 ways

  1. Anonymous inner class that extends a class.
  2. Anonymous inner class that implements an interface.
  3. Anonymous inner class that defined as arguments of method / constructor.

2. Anonymous class example

class Greeter {
    
    public void wish() {
        System.out.println("Hello");
    }
}
public class Test {
    
    public static void main(String[] args) {
         
        // Anonymous Inner class 1
        Greeter englishGreet = new Greeter() {
            // This is equivalent code of extending Greeter class and then overriding wish() method
            public void wish() {
                System.out.println("Hi");
            }
        };
        
        // Anonymous Inner class 2
        Greeter frenchGreet = new Greeter() {
                // This is equivalent code of extending Greeter class and then overriding wish() method
                public void wish() {
                    System.out.println("tout le monde");
                }
         };
        
        englishGreet.wish(); // Hi
        frenchGreet.wish(); // tout le monde
        Greeter britanGreet = new Greeter();
        britanGreet.wish(); // Hello
    }
}

Output :

Hi
tout le monde
Hello

2. Anonymous class that extends a class

Following is the example for Anonymous inner class that extends a class.
And you can declare the following in anonymous classes:
1. Fields
2. Extra methods (even if they do not implement any methods of the super type)
3. Instance initializers
4. Local classes
5. However, you cannot declare constructors in an anonymous class.

Inside Anonymous inner classes we can take or declare new methods but outside of anonymous inner classes we can’t call these methods directly because we are depending on parent reference.

2.1. Example 1

public class Test {
    
    public static void main(String[] args) {
         
        // Annonymous Inner class
        Greeter greeter = new Greeter() {
            
            // This is equivalent code of extending Greeter class and then overriding wish() method
            public void wish() {
                System.out.println("Hi");
                frenchWish();// Only can access inside this anonymous class
            }
            
            String frenchwish = "tout le monde"; // Can declare local variables
            //static String spanishWish = "mundo"; //not allowed, Only static constants allowed
            static final String spanWish = "mundo"; // Can declare static constants
            
            //Can write its own methods inside anonymous inner class
            public void frenchWish() {
                
                System.out.println(frenchwish);
                System.out.println(spanWish);
            }
        };
        
        greeter.wish(); // Hi
        // Can't call anonymous inner class methods, because it's depending on parent reference
        // p.frenchWish();
        Greeter p1 = new Greeter();
        p1.wish();//Hello
    }
}

Output :

Hi
tout le monde
mundo
Hello

2.2. Example 2 

class Test {
    
    public static void main(String[] args) {
        
        //Anonymous class extending Thread class and overriding run()
        Thread thread = new Thread() {
            
            public void run() {
                
                for(int i=0; i<5; i++) {
                    
                    System.out.println("Test thread");
                }
            }
        };
        
        thread.start();
        
        for(int i=0; i<5; i++) {
            System.out.println("Main Thread");
        }
    }
}

Output : thread execution order might be different for you, it’s depends on thread scheduler.

Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Test thread
Test thread
Test thread
Test thread
Test thread

3. Java anonymous class that implements an interface

Example :

public class AnonymousClassRunnableExample {

	public static void main(String[] args) {

		// Implementing Runnable Interface and overriding run()
		Runnable r = new Runnable() {

			public void run() {

				for (int i = 0; i < 5; i++) {
					System.out.println("Test Thread");
				}
			}
		};

		Thread thread = new Thread(r);
		thread.start();

		for (int i = 0; i < 4; i++) {
			System.out.println("Main Thread");
		}
	}
}

Output :

Main Thread
Main Thread
Main Thread
Main Thread
Test Thread
Test Thread
Test Thread
Test Thread
Test Thread

4. Java Anonymous class as argument of method / constructor

4.1. Example 1

class Test {
    
    public static void main(String[] args) {
        
        // Anonymous inner class as constructor argument
        new Thread( new Runnable() {
            
            public void run(){
                
                for(int i=0; i<5; i++) {
                    System.out.println("Test Thread");
                }
            }
        }).start();
        
        for(int i=0; i<5; i++){
            System.out.println("Main Thread");
        }
    }
}

Output :

Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Test Thread
Test Thread
Test Thread
Test Thread
Test Thread

4.2. Example 2

public class AnonymousClassAsMethodArgExample2 {
	
	public static void main(String[] args) {
		
		List<String> list = Arrays.asList("Peter", "Ashja", "Zahreen", "Mike");

		Set<String> names = new TreeSet<String>();
		names.addAll(list);
		
		System.out.println(names);
		
		// reverse order by passing anonymous class as argument to constructor
		names = new TreeSet<String>(new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				return o2.compareTo(o1);
			}
		});
		
		names.addAll(list);
		System.out.println(names);
		
	}
}

Output :

[Ashja, Mike, Peter, Zahreen]
[Zahreen, Peter, Mike, Ashja]

5. General class vs java anonymous class

General  ClassesAnonymous Inner Classes
1. A general class can extends only one class at a time.1. Anonymous inner class also can extends only one class at a time.
2. A general class can implement any no. Of interfaces at a time.2. Anonymous inner class can implement only one interface at a time.
3. A general class can extends a class and can implement an interface    simultaneously.3. anonymous inner class can extends a class or can implements an interface but not both simultaneously.
4. In normal Java class we can write constructor because we know name of the class.4. Anonymous inner class we can’t write constructor because anonymous inner class not having any name.

Reference

  1. Java document

Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Follow him on LinkedIn or Twitter or Facebook

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories