w3resource

Java Anonymous Class Implementing an Interface Example

Java Nested Classes: Exercise-4 with Solution

Anonymous Class Exercise:
Write a Java program to create an interface called Greeting with a method sayHello(). In the main method, create an anonymous class that implements the Greeting interface and override the sayHello() method to print "Hello, World!". Call the sayHello() method.

Sample Solution:

Java Code:

Main.java

// Main class containing the main method
public class Main {
    public static void main(String[] args) {
        // Creating an anonymous class that implements the Greeting interface
        Greeting greeting = new Greeting() {
            @Override
            public void sayHello() {
                // Overriding the sayHello method to print "Hello, World!"
                System.out.println("Hello, World!");
            }
        };

        // Calling the sayHello method of the anonymous class
        greeting.sayHello();
    }
}

Output:

Hello, World!

Explanation:

  • Interface Greeting: Defines a method sayHello() that must be implemented by any class that implements this interface.
  • Main class: Contains the main method where the execution starts.
  • Anonymous class: Implements the Greeting interface and overrides the sayHello() method to print "Hello, World!".
  • Override sayHello(): Provides the implementation for the sayHello() method defined in the Greeting interface.
  • Calling sayHello(): The overridden method is called to print the greeting message.

Note on Java Nested Classes:

  • In this exercise, the Java nested classes concept is demonstrated through the use of an anonymous class.
  • An anonymous class is a class without a name and is used to instantiate objects with certain modifications, such as implementing an interface or extending another class.
  • This allows for concise and flexible code, particularly useful for implementing simple interfaces or abstract classes without cluttering the code with additional class definitions.
  • The example shows how to implement the Greeting interface using an anonymous class.
  • The anonymous class provides an implementation for the sayHello() method.
  • The sayHello() method is invoked to display a greeting message.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java Static Members Previous: Java Program with Local Class in Method - Car and Engine.
Java Static Members Next: Java Inner Class Accessing Outer Class Members Example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/nested-classes/java-nested-classes-exercise-4.php