final:
- Final is a keyword/modifier.
- A member become constant if we define it as final hence cannot be modified.
- We can apply final to Class or Method or Variable.
If Class is final, cannot be inherited:
final class A { // logic } class B extends A /* Error: final class-A cannot be extended */ { // logic } |
If Method is final, cannot be overridden:
class A { void m1(){ … } final void m2(){ … } } | class B extends A { void m1(){ … } void m2(){ /* Error : */ … } } |
If the variable is final become constant and cannot be modified:
class Test { static final double PI = 3.142 ; public static void main(String[] args) { Test.PI = 3.1412 ; // Error : can’t modify } } |
Why constructor cannot be final?
- final is used for fixing, avoid overriding and inheriting.
- Constructor cannot be final, because it can’t be inherited/overridden.