Advertisement
Google Ad Slot: content-top
Java final keyword
The final keyword in Java is a modifier used to impose restrictions on variables, methods, and classes. It is part of the Java programming language to ensure immutability, prevent overriding, and prevent inheritance in various scenarios.
Final Variables:
- Purpose: A
finalvariable becomes a constant once it is initialized. Its value cannot be changed after being assigned.
Syntax:
final dataType variableName = value;
Example
class Example {
final int MAX_VALUE = 100; // Constant variable
void display() {
// MAX_VALUE = 200; // Compilation Error: Cannot reassign a final variable
System.out.println("MAX_VALUE: " + MAX_VALUE);
}
}
public class Main {
public static void main(String[] args) {
Example obj = new Example();
obj.display();
}
}
Final Methods:
- Purpose: A
finalmethod cannot be overridden in a subclass, ensuring that the method's implementation remains the same in all derived classes.
Syntax:
class Parent {
final void display() {
System.out.println("This is a final method.");
}
}
class Child extends Parent {
// void display() { } // Compilation Error: Cannot override the final method
}
Example
class Parent {
final void display() {
System.out.println("Final method in Parent class.");
}
}
class Child extends Parent {
void show() {
System.out.println("Method in Child class.");
}
}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
obj.display(); // Calls the final method from Parent
obj.show();
}
}
Final Classes:
- Purpose: A
finalclass cannot be extended, preventing inheritance. It is used to make the class immutable or to prevent modification of its behavior.
Syntax:
final class FinalClass {
void display() {
System.out.println("This is a final class.");
}
}
// class Child extends FinalClass { } // Compilation Error: Cannot inherit from final class
Example
final class FinalClass {
void display() {
System.out.println("This is a final class.");
}
}
public class Main {
public static void main(String[] args) {
FinalClass obj = new FinalClass();
obj.display();
}
}