Write a Java program to call a method using the anonymous object


This Java program defines a class Demo which has a method printHello() that prints the message "Hello World" to the console when called. The program also defines a Anonymous_Object class which creates a new instance of the Demo class using the new keyword, and then calls the printHello() method on that instance.

When the Demo instance is created, the constructor of the Demo class is called, which prints the message "Constructor" to the console.

Source Code

public class Anonymous_Object
{
	public static void main(String args[])
	{
		new Demo().printHello();
	}
}
class Demo
{
	void printHello()
	{
		System.out.println("Hello World");
	}
	Demo()
	{
		System.out.println("Constructor");
	}
}

Output

Constructor
Hello World