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:
FinalClass
is declared as afinal
class, which means it cannot be subclassed. Attempting to create a subclass ofFinalClass
(as shown in the commented code) will result in a compilation error.- Inside
FinalClass
, we have afinal
variable calledfinalVariable
, which cannot be modified after it’s initialized. - There’s also a
final
method calledfinalMethod
inFinalClass
, which cannot be overridden in any subclass. - In the
main
method, we create an object ofFinalClass
and demonstrate that we can access thefinalVariable
and call thefinalMethod
.
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