Final is using for three purpose:
- final is used to prevent method overriding
- final is used to prevent inherit a class
- final is used to make a variable constant
- final is used to prevent overriding: A method declared as final can’t be overridden.
1 2 3 4 5 6 7 8 9 10 11 | class A { final void show() { } } class B extends A { void show() { //error, can’t override } } |
Because show() declared as final, it can’t be overridden in B. If we attempt to do so, a compile time error will result.
2. final to prevent inheritance: Sometimes we
1 2 3 4 5 6 | final class A { } class B extends A { // error, can’t subclass A } |
3. final as constant: A variable can be declared as constant with the keyword final. It must be initialize while declaring. Once we declare a variable with keyword final it can’t be reinitialized in the program. It is similar to the const in c/c++.
1 2 | final int x = 10; x = 45; //error |