What are inner class and anonymous class?-

Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.

In Java, inner classes and anonymous classes are both features related to class declarations within other classes. Here’s a brief overview of each:

  1. Inner Class:
    • An inner class is a class that is defined within another class.
    • It can have access to the members (fields and methods) of the outer class, including private members.
    • Inner classes are used for logical grouping of classes and improved encapsulation.

    Example:

    java
    class Outer {
    // Outer class members
    class Inner {
    // Inner class members
    }
    }

  2. Anonymous Class:
    • An anonymous class is a class without a name that is defined on the fly at the point where it is needed.
    • It is often used for implementing interfaces or extending classes without creating a separate named class.
    • Anonymous classes are typically used for short-lived instances.

    Example (implementing an interface):

    java
    MyInterface obj = new MyInterface() {
    // Anonymous class implementation of the interface
    // Overriding interface methods here
    };

    Example (extending a class):

    java
    MyClass obj = new MyClass() {
    // Anonymous class extending MyClass
    // Overriding methods of MyClass here
    };

In summary, inner classes are named classes defined within another class, while anonymous classes are unnamed classes created at the point of use, often for implementing interfaces or extending classes.