Anonymous Inner Classes
java.lang.Object is used.
Anonymous classes are given a name by the compiler and they are treated as local inner classes. This means that anonymous classes can access members of the enclosing class regardless of their access modifiers and they can access final variables declared in the enclosing block of code.
The next example provides the basic syntax and shows how complexity can add up when the concept is “abused”;
package com.littletutorials.nested;
public class AnonymousTest
{
private String s = "test member access";
public void test(final String s)
{
// anonymous instance as a variable
Runnable r = new Runnable()
{
@Override
public void run()
{
System.out.print(getClass().getName() + " inner in ");
System.out.println(getClass().getEnclosingClass());
System.out.println("in anonymous class 1");
System.out.println(AnonymousTest.this.s);
}
};
Thread t1 = new Thread(r, "anonymous 1");
// anonymous instance as a parameter
Thread t2 = new Thread (new Runnable()
{
int a = 5;
@Override
public void run()
{
System.out.print(getClass().getName() + " inner in ");
System.out.println(getClass().getEnclosingClass());
System.out.println("in anonymous class 2");
System.out.println(s);
// anonymous instance inside another anonymous class
Thread t3 = new Thread (new Runnable()
{
@Override
public void run()
{
System.out.print(getClass().getName() + " inner in ");
System.out.println(getClass().getEnclosingClass());
System.out.println("in anonymous class 3");
System.out.println("a = " + a);
}
});
t3.start();
try
{
t3.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}, "anonymous 2");
try
{
t1.start();
t1.join();
t2.start();
t2.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new AnonymousTest().test("final parameter");
}
}
The output of the execution reveals the naming conventions used by the compiler for anonymous classes:
com.littletutorials.nested.AnonymousTest$1 inner in class com.littletutorials.nested.AnonymousTest
in anonymous class 1
test member access
com.littletutorials.nested.AnonymousTest$2 inner in class com.littletutorials.nested.AnonymousTest
in anonymous class 2
final parameter
com.littletutorials.nested.AnonymousTest$2$1 inner in class com.littletutorials.nested.AnonymousTest$2
in anonymous class 3
a = 5
As you can see each anonymous class is numbered in the order of declaration in the enclosing class.
Usually anonymous classes are used for short non reusable implementations. Examples are runnable instances, listeners etc.
This post is part of a series explaining the Java concept of defining classes in other classes:
- Static Nested Classes
- Static Nested Interfaces
- Inner Classes
- Local Inner Classes
- Anonymous Inner Classes
