Learn how to use the final
keyword with variables, methods, and classes in Java.
Explore rules, examples, and FAQs to understand its importance.
final
in Java?In Java, final
is a keyword used to restrict the user. It can be applied to variables, methods, and classes.
public class FinalVariableInitializationExample {
// Final instance variable initialized at the time of declaration
final int x = 10;
// Blank final instance variable, must be initialized in constructor
final int y;
// Constructor to initialize the blank final variable
public FinalVariableInitializationExample() {
y = 20; // Initialization of final variable 'y'
}
public static void main(String[] args) {
// Create an object of the class
FinalVariableInitializationExample obj = new FinalVariableInitializationExample();
// Access and print final variables
System.out.println("x: " + obj.x); // Output: 10
System.out.println("y: " + obj.y); // Output: 20
}
}
final
variable cannot be changed.
Attempting reassignment leads to a compilation error.
public class FinalVariableReassignmentExample {
final int x = 10;
public void modifyFinalVariable() {
// x = 20; // error: cannot assign a value to final variable
}
public static void main(String[] args) {
System.out.println("x: " + new FinalVariableReassignmentExample().x);
}
}
final
.
Their values cannot be reassigned within the method.
public class FinalParameterExample {
public void printValue(final int x) {
System.out.println("x: " + x);
// x = 20; // error: cannot assign a value to final parameter
}
public static void main(String[] args) {
new FinalParameterExample().printValue(10);
}
}
final
method cannot be overridden in a subclass.class Parent {
public final void show() {
System.out.println("This is a final method.");
}
}
class Child extends Parent {
// public void show() { } // error: cannot override final method
}
public class FinalMethodExample {
public static void main(String[] args) {
new Child().show();
}
}
final
class cannot be inherited.java.lang.String
).
final class Vehicle {
void display() {
System.out.println("This is a final class.");
}
}
// class Car extends Vehicle { } // error: cannot inherit from final class
public class FinalClassExample {
public static void main(String[] args) {
new Vehicle().display();
}
}
public class AnonymousClassExample {
public void printValue() {
final int x = 10; // effectively final
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Value of x: " + x);
// x = 20; // Error: cannot assign a value to final variable
}
};
r.run();
}
public static void main(String[] args) {
new AnonymousClassExample().printValue();
}
}
The final
keyword in Java is used to restrict the user. It can be applied to variables, methods, and classes. A final
variable cannot be reassigned, a final
method cannot be overridden, and a final
class cannot be subclassed.
Topic: Final-keyword | Language: Java