w3resource

Java Anonymous Class Implementing Abstract Class Example

Java Nested Classes: Exercise-8 with Solution

Anonymous Class Implementing Abstract Class:
Write a Java program to create an abstract class called Animal with an abstract method makeSound(). In the main method, create an anonymous class that extends Animal and override the makeSound() method to print "Meow" for a cat. Call the makeSound() method.

Sample Solution:

Java Code:

Animal.java

// Abstract class Animal with an abstract method makeSound
abstract class Animal {
    // Abstract method makeSound
    abstract void makeSound();
}

Main.java

// Main class to demonstrate anonymous class
public class Main {
    // Main method
    public static void main(String[] args) {
        // Creating an anonymous class that extends Animal and overrides makeSound method
        Animal cat = new Animal() {
            // Overriding the makeSound method
            @Override
            void makeSound() {
                System.out.println("Meow");
            }
        };

        // Calling the makeSound method
        cat.makeSound();
    }
}

Output:

Meow

Explanation:

  • Abstract class Animal: Contains an abstract method makeSound().
  • Main class: Contains the main method to demonstrate the usage of the anonymous class.
  • Anonymous class: Extends the Animal class and overrides the makeSound() method to print "Meow".
  • Method makeSound: Defined inside the anonymous class to provide the implementation for the abstract method.
  • Instantiation and method call: In the main method, an instance of the anonymous class is created, and the makeSound() method is called to print "Meow".

Note on Java Nested Classes:

Java nested classes can be anonymous, meaning they do not have a class name and are used to instantiate objects with certain "one-time" behavior. In this exercise, an anonymous class extends the abstract class Animal and provides an implementation for the "makeSound()" method. This allows for quick and concise definition of a subclass and its methods, making the code more readable and easier to manage when only a single instance with specific behavior is needed.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java Static Members Previous: Java Local Class Accessing Local Variables Example.
Java Static Members Next: Java Inner Class with Constructor 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-8.php