Back to the 2020 paper

Module III: Basics of Web Programming

20207m

With suitable code segments, illustrate various uses of 'final' keyword. Discuss about anonymous inner classes.

Worked SolutionAI Assisted

Answer: Uses of 'final' Keyword and Anonymous Inner Classes in Java


Part 1: Various Uses of the 'final' Keyword in Java

In Java, the final non-access modifier is used to impose restrictions and enforce immutability across three primary programming levels: variables, methods, and classes.

                               +-----------------------------+
                               |     USES OF 'final' KEYWORD |
                               +--------------+--------------+
                                              |
                     +------------------------+------------------------+
                     |                        |                        |
                     v                        v                        v
           +--------------------+   +--------------------+   +--------------------+
           |   Final Variable   |   |    Final Method    |   |    Final Class     |
           | (Constant / No Re- |   |  (Cannot Override) |   | (Cannot Inherit /  |
           |     assignment)    |   |                    |   |    Subclass)       |
           +--------------------+   +--------------------+   +--------------------+

1. final Variable (Constants)

  • A final variable's value cannot be modified once assigned (acts as a constant).
  • Can be initialized at declaration or inside a constructor (blank final variable).
class Circle {
    // Final constant
    final double PI = 3.14159265359;
    final double radius; // Blank final variable

    Circle(double r) {
        this.radius = r; // Initialized in constructor
    }

    void changeValue() {
        // PI = 3.14; // COMPILE ERROR: Cannot assign a value to final variable PI
    }
}

2. final Method (Prevents Method Overriding)

  • Declaring a method as final prevents subclasses from overriding or altering its core implementation (critical for security and invariant business logic).
class ParentService {
    // Final method cannot be overridden
    final void authenticateUser(String username, String password) {
        System.out.println("Executing secure internal authentication logic.");
    }
}

class ChildService extends ParentService {
    // COMPILE ERROR: authenticateUser() in ChildService cannot override authenticateUser() in ParentService
    /*
    void authenticateUser(String username, String password) {
        System.out.println("Trying to bypass authentication");
    }
    */
}

3. final Class (Prevents Inheritance)

  • A final class cannot be extended by any other class (e.g., java.lang.String, java.lang.System, Wrapper classes).
final class SecureToken {
    String tokenValue = "XYZ-123";
}

// COMPILE ERROR: Cannot inherit from final class SecureToken
// class CustomToken extends SecureToken { }

Part 2: Anonymous Inner Classes in Java

1. Concept & Definition

An Anonymous Inner Class in Java is an inner class that has no formal class name and is simultaneously declared and instantiated in a single expression.

  • It is used when you need to override methods of a class or implement an interface for one-time local use, avoiding the overhead of creating a separate .java class file.

2. Syntax & Implementation Example

// Interface with a single method
interface GreetingService {
    void greet(String name);
}

public class AnonymousInnerClassDemo {
    public static void main(String[] args) {
        
        // Creating and instantiating an Anonymous Inner Class
        GreetingService hindiGreeting = new GreetingService() {
            @Override
            public void greet(String name) {
                System.out.println("Namaste, " + name + "!");
            }
        };

        // Another anonymous instance with different behavior
        GreetingService englishGreeting = new GreetingService() {
            @Override
            public void greet(String name) {
                System.out.println("Welcome, " + name + "!");
            }
        };

        hindiGreeting.greet("Rohan");
        englishGreeting.greet("Rohan");

        // Example with Thread / Runnable
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Background worker thread running inside anonymous class.");
            }
        });
        t.start();
    }
}

3. Key Characteristics of Anonymous Inner Classes:

  1. No Constructor: Since it has no name, it cannot define a constructor.
  2. Access Rules: Can access instance variables of the enclosing class and local variables in scope (provided the local variables are final or effectively final).
  3. Compiled Name: The compiler generates class files with numbering: OuterClassName1.class,OuterClassName1.class`, `OuterClassName2.class.

Similar questions