How to use the final modifier in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 10-Jan-2018 07:18:02
Advertisements