PREV NEXT
Java Final Keyword:
The keyword ‘final’ in java is used to restrict access of an entity. The keyword ‘final’ can be used with,
- Variable
- Method
- Class
Final Variable:
If a variable is declared as final, its value cannot be changed. Final variable can be initialized only once – either at the declaration time or inside a constructor. Final variables are similar to constants.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Demo { final int MAX = 100; //final variable void method() { MAX = MAX+50; //Will cause runtime exception } public static void main(String args[]) { Demo d = new Demo(); d.method(); } } |
Note:
- A blank final variable is a final variable, which is not initialized while declaration. It can be assigned only once.
- Both Parameters and local variables can also be declared as final. Value of such final members cannot be changed within the method.
Final Method:
When a method is declared as final, it cannot be overridden in any of its subclasses. But, overloading is possible with final method.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Class A { final void method1() { System.out.println(“final method”); } } Class B extends A { void method1() { //compile time error System.out.println(“final method overriden”); } public static void main(String args[]) { A a = new A(); a.method1(); } } |
Final Class:
When a class is declared as final, it cannot be inherited further.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
final class A { //final class A } class B extends A { //compile time error void method() { System.out.println(“final method”); } public static void main(String args[]) { B b = new B(); b.method(); } } |