In Java, the final
keyword can be used while declaring an entity.
Using the final keyword means that the value can’t be modified in the future. This entity can be - but is not limited to - a variable, a class or a method.
// declaring a final variableclass FinalVariable {final int var = 50;var = 60 //This line would give an error}
For a final
reference variable you cannot change what object it refers to. You can, however, modify the object itself.
class Reference{public int value = 5;}class frVariable {public static void FinalReference( String args[] ) {final Reference example = new Reference(); //declarationexample.value = 6; // Modifying the object creates no disturbanceReference another = new Reference();example = another; // Attempting to change the object it refers to, creates an error}}
class finalParameter {public static void example( final int parameter ) {parameter = 4; //attempting to reassign a value to a parameter throws an error}}
A method, declared with the final
keyword, cannot be overridden or hidden by subclasses.
// declaring a final methodclass Base{public final void finalMethod(){System.out.print("Base");}}class Derived extends Base{public final void finalMethod() { //Overriding the final method throws an errorSystem.out.print("Derived");}}
// declaring a final classfinal class FinalClass {//...}class Subclass extends FinalClass{ //attempting to subclass a final class throws an error//...}
Free Resources