Explain inner classes in Java.

Inner classes are classes declared inside another class. They help organize related code, improve encapsulation, and allow the inner class to directly access members of the outer class, including private fields and methods.

Key Points: • Inner classes are commonly used when a class is tightly coupled with another class. • They can access all members of the enclosing class, even private ones. • Java supports four types of nested classes: Member Inner Class, Static Nested Class, Local Inner Class, and Anonymous Inner Class. • Using inner classes improves code readability by keeping related functionality together.

Example: Consider a Car class and an Engine class. If the Engine is only relevant to the Car, defining Engine as an inner class keeps the design cleaner and prevents unnecessary exposure to other parts of the application.

Code Example:

class Outer {

    private String message = "Hello from Outer Class";

    class Inner {
        void display() {
            System.out.println(message);
        }
    }

    public static void main(String[] args) {
        Outer outer = new Outer();
        Outer.Inner inner = outer.new Inner();
        inner.display();
    }
}

Interview Tip: A concise interview answer is: Inner classes are classes defined inside another class. They are used to logically group related functionality, enhance encapsulation, and provide direct access to the outer class members. Java supports member inner classes, static nested classes, local classes, and anonymous classes.