Final Keyword in java are reserved word and it can be applied to member variables, methods, class and local variables in Java.
We will cover following topics in detail.
At variable level
At method level
At class level
final variable :-
Any variable either member variable or local variable (declared inside method or block) precede with final keyword is called final variable.
We cannot change the value of a final variable once it is initialized. Lets have a look at the below picture.
In above picture representation we are trying to assign a new value to "junk"" variable which is final. so here we will get a compile time error.
final method :-
A java method with final keyword is called final method and it can not be overridden in sub-class.
You should make a method final in java if you think itís complete and its behavior should remain constant in
sub-classes. Final methods are faster than non-final methods because they are not required to be resolved during
run-time and they are bonded on compile time.Let's have a look at the below code :-
In above example we are trying to override the "fly()" from Duck class in FlyDuck class so
here we will get a compile time error.because final methods can not be overridden in sub-class.
final class :-
A java class with final keyword is called final class and it can not be have any sub-class. There are several classes
in Java are final e.g. System, String, Integer and other wrapper classes. Refer below picture :-
In above example we are trying to extends the "Duck" into "FlyDuck" class so
here we will get a compile time error. because A final class can not have any sub-class.