How to use the final modifier in Java?


The final modifier can be associated with methods, classes and variables. Once declared final −

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

Example

Live Demo

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

Updated on: 30-Jul-2019

905 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements