×

Java Programs

Java Practice

Java program to create an anonymous object

Learn how to create an anonymous object in Java?
Submitted by Nidhi, on March 25, 2022

Problem statement

In this program, we will create an anonymous object. An object which has no reference variable is called an anonymous object.

Java program to create an anonymous object

The source code to create an anonymous object is given below. The given program is compiled and executed successfully.

// Java program to create an anonymous 
// object.

class Sample {
  Sample() {
    System.out.println("Constructor called");
  }

}
public class Main {
  public static void main(String[] args) {
    new Sample();
  }
}

Output

Constructor called

Explanation

In the above program, we created two classes Sample and Main. The Sample class contains a constructor.

The Main class contains a method main(). The main() method is the entry point for the program, here we created an anonymous object of the Sample class and called the constructor of Sample class.

Java Class and Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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