Interface Implementation with Anonymous Classes in Java


Write a Java program to demonstrate interface implementation with anonymous classes

  • The Message interface declares a method sendMessage() without providing an implementation.
  • In the main method of the Main class, we create an instance of an anonymous inner class that implements the Message interface.
  • Inside the anonymous inner class, we provide the implementation for the sendMessage() method by overriding it.
  • Finally, we call the sendMessage() method on the email object, which executes the implementation provided in the anonymous inner class, resulting in printing "Sending an email message" to the console.

Source Code

interface Message
{
	void sendMessage();
}
 
public class Main
{
	public static void main(String[] args)
	{
		Message email = new Message()
		{
			@Override
			public void sendMessage()
			{
				System.out.println("Sending an email message");
			}
		};
 
		email.sendMessage();
	}
}

Output

Sending an email message

Example Programs