Java Anonymous Class

A class that has no name is known as anonymous class. Java Anonymous class can be created in two ways:

Class
Interface
For more information please read https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#accessing

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.


An anonymous class is an expression. The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code.

Consider the instantiation of the spanishHello object:

Hello spanishHello = new Hello() {
    String name = "Sandip";
    @Override
    public void hello() {
        helloSomeone(name);
    }
    @Override
    public void helloSomeone(String name) {
        System.out.println("Hola, " + name);
    }
};

The anonymous class expression consists of the following:

The new operator
The name of an interface to implement or a class to extend.
Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression.
A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.

Because an anonymous class definition is an expression, it must be part of a statement.
Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:

An anonymous class has access to the members of its enclosing class.
An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.
Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing scope that have the same name.

Anonymous classes also have the same restrictions as local classes with respect to their members:

You cannot declare static initializers or member interfaces in an anonymous class.
An anonymous class can have static members provided that they are constant variables.

The following can be declared in anonymous classes:

Fields
Extra methods (even if they do not implement any methods of the supertype)
Instance initializers
Local classes

However, you cannot declare constructors in an anonymous class.
Prerequisites
The following configurations are required in order to run the application
Eclipse Mars
JDK 1.8
Have maven installed and configured
JPA dependencies in pom.xml
Now we will see the below steps how to create a maven based spring project in Eclipse.
Step 1. Create a standalone maven project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

maven-arctype-quickstart
Now enter the required fields (Group Id, Artifact Id) as shown below
Group Id : com.roytuts
Artifact Id : java
Step 2. Modify the pom.xml file as shown below.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.roytuts</groupId>
	<artifactId>java</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>java</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Step 3. If you see JRE System Library[J2SE-1.5] then change the version by below process

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.5], click on Edit button and select the appropriate jdk 1.8 from the next window. Click on Finish then Ok.

Anonymous Class example by extending a Class

package com.roytuts.java.anonymous.classes;
public class HelloAnonymousClass {
	abstract class Hello {
		public abstract void hello();
		public abstract void helloSomeone(String name);
	}
	public void sayHello() {
		class EnglishHello extends Hello {
			String name = "Rahul";
			@Override
			public void hello() {
				helloSomeone(name);
			}
			@Override
			public void helloSomeone(String name) {
				System.out.println("Hello, " + name);
			}
		}
		Hello englishHello = new EnglishHello();
		Hello FrenchHello = new Hello() {
			String name = "Sumit";
			@Override
			public void hello() {
				helloSomeone(name);
			}
			@Override
			public void helloSomeone(String name) {
				System.out.println("Salut, " + name);
			}
		};
		Hello spanishHello = new Hello() {
			String name = "Sandip";
			@Override
			public void hello() {
				helloSomeone(name);
			}
			@Override
			public void helloSomeone(String name) {
				System.out.println("Hola, " + name);
			}
		};
		Hello germanHello = new Hello() {
			String name = "Liton";
			@Override
			public void hello() {
				helloSomeone(name);
			}
			@Override
			public void helloSomeone(String name) {
				System.out.println("Hallo, " + name);
			}
		};
		englishHello.hello();
		FrenchHello.hello();
		spanishHello.hello();
		germanHello.hello();
	}
	public static void main(String[] args) {
		HelloAnonymousClass anonymousClass = new HelloAnonymousClass();
		anonymousClass.sayHello();
	}
}

If you run the above class, you will get the following output

Hello, Rahul
Salut, Sumit
Hola, Sandip
Hallo, Liton

Anonymous Class example by implementing an Interface

package com.roytuts.java.anonymous.classes;
public class HelloAnonymousInterface {
	interface Hello {
		public void hello();
		public void helloSomeone(String name);
	}
	public void sayHello() {
		class EnglishHello implements Hello {
			String name = "Rahul";
			@Override
			public void hello() {
				helloSomeone(name);
			}
			@Override
			public void helloSomeone(String name) {
				System.out.println("Hello, " + name);
			}
		}
		Hello englishHello = new EnglishHello();
		Hello FrenchHello = new Hello() {
			String name = "Sumit";
			@Override
			public void hello() {
				helloSomeone(name);
			}
			@Override
			public void helloSomeone(String name) {
				System.out.println("Salut, " + name);
			}
		};
		Hello spanishHello = new Hello() {
			String name = "Sandip";
			@Override
			public void hello() {
				helloSomeone(name);
			}
			@Override
			public void helloSomeone(String name) {
				System.out.println("Hola, " + name);
			}
		};
		Hello germanHello = new Hello() {
			String name = "Liton";
			@Override
			public void hello() {
				helloSomeone(name);
			}
			@Override
			public void helloSomeone(String name) {
				System.out.println("Hallo, " + name);
			}
		};
		englishHello.hello();
		FrenchHello.hello();
		spanishHello.hello();
		germanHello.hello();
	}
	public static void main(String[] args) {
		HelloAnonymousInterface anonymousInterface = new HelloAnonymousInterface();
		anonymousInterface.sayHello();
	}
}

If you run the above class, you will see the following output

Hello, Rahul
Salut, Sumit
Hola, Sandip
Hallo, Liton

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *