What is the final access modifier in java?

In Java, the final access modifier is used to restrict the usage of variables, methods, and classes in various ways. When something is declared as final, it means its value or behavior cannot be changed after initialization or declaration.

Uses of final in Java:

  1. Final Variables:
  2. A final variable is a constant. Once it is assigned a value, it cannot be reassigned.
  3. If a final variable is not initialized at the time of declaration, it must be initialized in the constructor or an initializer block.

Example:

```java

public class Example {

final int MAX_VALUE \= 100;

   void display() {
       // MAX_VALUE = 200; // This will cause a compilation error
       System.out.println("Max Value: " + MAX_VALUE);
   }

}

```

  1. Final Methods:
  2. A final method cannot be overridden by subclasses. This ensures that the method’s behavior remains consistent across all subclasses.

Example:

```java

class Parent {

final void display() {

System.out.println("This is a final method.");

}

}

class Child extends Parent {

// void display() { } // This will cause a compilation error

}

```

  1. Final Classes:
  2. A final class cannot be subclassed. This is useful when you want to prevent inheritance, ensuring that the class’s implementation cannot be altered.

Example:

```java

final class Utility {

void performAction() {

System.out.println("Performing action.");

}

}

// class ExtendedUtility extends Utility { } // This will cause a compilation error

```


Follow-up Question

  1. What happens if you try to reassign a final variable in Java?
  2. Answer: If you try to reassign a final variable, the Java compiler will throw a compilation error, as the value of a final variable cannot be changed once it has been initialized.