The following code example demonstrates How to Use final Keyword in Java.

Problem Statement

Create an application to show the usage of the final keyword with class, variables, and methods in java.

Solution

// A final class that cannot be subclassed
final class FinalClass {
    // A final variable that cannot be modified
    final int finalVariable = 10;

    // A final method that cannot be overridden
    final void finalMethod() {
        System.out.println("This is a final method.");
    }
}

// This class attempts to extend the final class, which will result in a compilation error
// class Subclass extends FinalClass {}

public class FinalDemo {
    public static void main(String[] args) {
        // Create an object of the FinalClass
        FinalClass finalObject = new FinalClass();

        // Access the final variable
        int value = finalObject.finalVariable;
        System.out.println("Final Variable: " + value);

        // Call the final method
        finalObject.finalMethod();
    }
}

In this program:

  1. FinalClass is declared as a final class, which means it cannot be subclassed. Attempting to create a subclass of FinalClass (as shown in the commented code) will result in a compilation error.
  2. Inside FinalClass, we have a final variable called finalVariable, which cannot be modified after it’s initialized.
  3. There’s also a final method called finalMethod in FinalClass, which cannot be overridden in any subclass.
  4. In the main method, we create an object of FinalClass and demonstrate that we can access the finalVariable and call the finalMethod.

In summary, this program illustrates the use of the final keyword with a class, variable, and method, showcasing that final elements cannot be extended, modified, or overridden once they are declared as final.



Further Reading

Spring Framework Practice Problems and Their Solutions

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

Java Practice Exercise

programmingempire

Princites