×

Java Programs

Java Practice

Java program to create an anonymous class by extending a class

Java example to create an anonymous class by extending a class.
Submitted by Nidhi, on May 07, 2022

Problem statement

In this program, we will implement an anonymous class inside a class by extending another class.

Java program to create an anonymous class by extending a class

The source code to create an anonymous class by extending a class is given below. The given program is compiled and executed successfully.

// Java program to create an anonymous class 
// by extending a class

class Sample {
  public void print() {
    System.out.println("Inside the Sample class");
  }
}

class Demo {
  public void createAnonymousClass() {
    // Anonymous class by extending Sample class
    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 2 classes Sample and Demo. We created an anonymous class by extending the Sample class into the Demo class.

In the main() method, we created the object of the Demo class and called the createAnonymousClass() method to create an anonymous class and called the print() method and printed the "Inside the anonymous class" method.

Java Class and Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.