bscodinglab

Final Keyword

The final keyword is used to create entities (variables, methods, and classes) that are immutable or cannot be overridden, extended, or modified, depending on where it is used. The exact behavior of final depends on where it is applied:

Final Variables :-

A final variable is a variable that cannot be modified after it has been assigned a value. Once a final variable is initialized, its value remains constant throughout its lifetime. Final variables are often used to create constants or to ensure that a variable’s value does not change accidentally, making your code more robust and predictable.

Example:-

final int constantValue = 10;

// You can’t change the value of constantValue after it’s set.

Final Methods :-

A final method is a method that cannot be overridden by subclasses. When a method is declared as final in a class, it means that the method’s implementation is fixed and cannot be changed in any subclass that extends the class containing the final method. This is often used to enforce a specific behavior that should not be altered by subclasses. This is often used to prevent subclasses from altering the behavior of a method defined in a superclass.

Example:-

class Parent

{

    final void myMethod()

            {

            // This method cannot be overridden by subclasses

            }

   }

Final Classes :-

When applied to a class, it means the class cannot be extended. a final class is a class that cannot be extended or subclassed. When a class is declared as final, it means that no other class can inherit from it. This provides a way to prevent further modification or extension of a class, ensuring that the class’s behavior and structure remain constant.

Example:-

final class MyFinalClass

      {

             // This class cannot be extended

       }