Java Basic Tutorial
Java Advance Tutorial
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
variable becomes a constant once it is initialized. Its value cannot be changed after being assigned.final dataType variableName = value;
Try it yourself
final
method cannot be overridden in a subclass, ensuring that the method's implementation remains the same in all derived classes.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 }
Try it yourself
final
class cannot be extended, preventing inheritance. It is used to make the class immutable or to prevent modification of its behavior.final class FinalClass { void display() { System.out.println("This is a final class."); } } // class Child extends FinalClass { } // Compilation Error: Cannot inherit from final class
Try it yourself