final keyword

What is final keyword?
The final keyword in java is used to restrict the user. 

It is used to make a variable as a constant, restrict method overriding, restrict inheritance. It is used at variable level, method level and class level. 

The java final keyword can be used with
  1. variable
  2. method
  3. class
Final keyword
1) final variable:
  • final variables are nothing but constants.
  • We cannot change the value of a final variable once it is initialized. 
Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class FinalVariableDemo {

 final int VALUE = 99;

 void myMethod() {
  VALUE = 101;
 }

 public static void main(String args[]) {
  Demo obj = new Demo();
  obj.myMethod();
 }
}

Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The final field Demo.MAX_VALUE cannot be assigned.

We got a compilation error in the above program because we tried to change the value of a final variable.

Note: It is considered as a good practice to have constant names in UPPER CASE(CAPS).

2) final method:
  • A final method cannot be overridden.
  • It means a sub class can call the final method of parent class without any issues but it cannot override it.
Example:
1
2
3
4
5
class ParentClass {
 final void demo() {
  System.out.println("ParentClass Class Method");
 }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class ChildClass extends ParentClass {
 void demo() {
  System.out.println("ChildClass Class Method");
 }

 public static void main(String args[]) {
  ChildClass obj = new ChildClass();
  obj.demo();
 }
}

Output:
The above program would throw a compilation error.

3) final class:
We cannot extend a final class. Consider the below example:
Example:
1
2
final class ParentClass {
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class ChildClass extends ParentClass {
 public void demo() {
  System.out.println("My Method");
 }

 public static void main(String args[]) {
  ABC obj = new ABC();
  obj.demo();
 }
}
Output:
Compile Time Error.


<-- Previous || Next -->

No comments:

Post a Comment