Write A Program In Java To Demonstrate The Use Of “final” Keyword.
In this program, we will create a java program to demonstrate the use of “final” keyword.
In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or extended. The final keyword can be applied to variables, methods and classes.
A final variable cannot be changed once it has been initialized. If a final variable has no value, it is called a blank final variable or uninitialized final variable. It can only be initialized in the constructor.
A final method cannot be overridden by subclasses. This means that if you have a method in a superclass that you do not want subclasses to change, you can declare it as final.
A final class cannot be extended by other classes. This means that if you have a class that you do not want other classes to inherit from, you can declare it as final.
Here's a program in java that show the use of "final" keyword:
public class FinalExample { // final variable final int x = 10;
// final method public final void display() { System.out.println("This is a final method."); }
public static void main(String[] args) { FinalExample obj = new FinalExample(); System.out.println("Value of x: " + obj.x); obj.display(); }}
Value of x: 10
In this example, we have a final variable x and a final method display(). The final keyword can be used to prevent a variable from being reassigned or to prevent a method from being overridden.
When we create an object of the FinalExample class and call its methods, we can see that the value of the final variable x cannot be changed. We also see that attempting to override the final method in a subclass produces an error.