Anonymous Classes are mainly for extending a class or implementing an interface for one time only.
First of all, let’s create a sample class called A.
public class A {
protected int number;
protected static String text = "Abc";
A() {
number = 100;
}
public void functionX() {
System.out.println("***functionX of Class A");
}
public void functionY() {
System.out.println("***functionY of Class A");
}
}
Anonymous Class can be defined as below.
Actually, Anonymous Class extends Class A and overrides functionX method.
public class Application {
public static void main(String[] args) {
int num = 100;
A a = new A() {
public void functionX() {
System.out.println("***functionX of Anonymous Class.");
System.out.println("Number (instance variable): " + number);
System.out.println("Text (class variable): " + text);
System.out.println("num (local variable): " + num);
}
};
a.functionX();
System.out.println();
a.functionY();
}
}
/*
OUTPUT:
-------
***functionX of Anonymous Class.
number (instance variable): 100
text (class variable): Abc
num (local variable): 100
***functionY of Class A
*/
Anonymous Class can also implement an interface.
interface B {
public void functionZ();
}
public class Application {
public static void main(String[] args) {
B b = new B() {
public void functionZ() {
System.out.println("functionZ of Anonymous Class");
}
};
b.functionZ();
}
}
/*
OUTPUT:
-------
functionZ of Anonymous Class
*/
Thanks for reading and please see another relevant post, Nested/Inner Classes in Java.