Home »
Java Programs »
Java Class and Object Programs
Java program to create an anonymous class by implementing an interface
Java example to create an anonymous class by implementing an interface.
Submitted by Nidhi, on May 07, 2022
Problem statement
In this program, we will implement an anonymous class inside a class by implementing an interface.
Java program to create an anonymous class by implementing an interface
The source code to create an anonymous class by implementing an interface is given below. The given program is compiled and executed successfully.
// Java program to create an anonymous class by
// implementing an interface
interface Sample {
public void print();
}
class Demo {
public void createAnonymousClass() {
// Anonymous class by implementing
// Sample interface
Sample s1 = new Sample() {
public void print() {
System.out.println("Inside the anonymous class.");
}
};
s1.print();
}
}
public class Main {
public static void main(String[] args) {
Demo d = new Demo();
d.createAnonymousClass();
}
}
Output
Inside the anonymous class.
Explanation
In the above program, we created a public class Main that contains a main() method. The main() method is the entry point for the program.
Here, we also created a Sample interface and Demo class. We created an anonymous class by implementing the Sample interface into the Demo class.
In the main() method, we created the object of the Demo class and called the createAnonymousClass() method to create the anonymous class and called the print() method and printed the "Inside the anonymous class" method.
Java Class and Object Programs »