Use the final Modifier in Java



In this article, we will learn to use the final modifier in Java. The final modifier can be associated with methods, classes, and variables. Once we declare it final ?

  • A final class cannot be instantiated.
  • A final method cannot be overridden.
  • A final variable cannot be reassigned.

These restrictions make code more predictable and can prevent unintentional modifications.

Steps to use the final modifier

Following are the steps to use the final modifier ?

  • First, we will define a class TestExample and declare a final variable value to demonstrate a constant that can't be reassigned.
  • Define two other final variables: BOXWIDTH as a public static final variable and TITLE as a static final variable, meaning these can't be changed and are accessible as constants.
  • Create a final method changeName() within TestExample to demonstrate that it cannot be overridden in a subclass.
  • Define a final class to show that any other class can't extend it.
  • In the main class, create an instance of FinalExample, then print the values of value, BOXWIDTH, and TITLE.
  • Call the changeName() method to confirm that it behaves as expected.

Java program to use the final modifier

Below is the Java program to use the final modifier ?
class TestExample {
   final int value = 10;
   public static final int BOXWIDTH = 6;
   static final String TITLE = "Manager";
   
   public final void changeName() {
      System.out.println("This is a final method");
   }
}
final class Demo{ }
public class FinalExample extends TestExample {
   public static void main(String args[]){
      FinalExample obj = new FinalExample();
      System.out.println(obj.value);
      System.out.println(obj.BOXWIDTH);
      System.out.println(obj.TITLE);
      obj.changeName();
   }
}

Output

10
6
Manager
This is a final method

Code explanation

In the above program, we demonstrate using the final modifier with variables, methods, and classes. The TestExample class has a final int value and two static final fields: BOXWIDTH and TITLE, which cannot be modified once set. The changeName() method in TestExample is declared as final, preventing it from being overridden in any subclasses. The Demo class is also declared as final, meaning no other class can extend it. Finally, in the FinalExample class, we create an object to access and print final variables and call the final method. This approach ensures the immutability of specific components in our code.

Updated on: 2024-10-25T23:40:58+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements