Usage of final keyword in java
Final Keyword In Java
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
final int ACK //(generally it is the convention to give capital letters to the final variable we declare)
It dosent occupy space in memory for multiple executions.
Its good that it saves memory
2) Java final method
If you make any method as final, you cannot override it.
- class bird{
- final void run(){System.out.println("running");}
- }
- class animal extends bird{
- void run(){System.out.println("animals eat birds");}
- public static void main(String args[]){
- animal lion= new animal();
- animal.run();
- }
- }
if u will test it will have compile error
3) Java final class
If you make any class as final, you cannot extend it.
- final class Bike{}
- class car extends Bike{
- void run(){System.out.println("running safely with 100kmph");}
- public static void main(String args[]){
- car mercedes= new car();
- car.run();
- }
- }
compile time error......
Now question arrises Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:
- class car{
- final void run(){System.out.println("running...");}
- }
- class cycle extends car{
- public static void main(String args[]){
- new cycle().run();
- }
- }
Another question Can we declare a constructor final?
No, because constructor is never inherited.
Final keyword in java
ReplyDeleteFinal keyword is mainly used at three places in java; at variable level to make a variable as a constant, at method level to Restrict method overriding, at class level to Restrict inheritance.
yes same thing is written based on the concepts you have mentioned
Deletefor variable to make it constant
for method to avoid overriding
for class to stop inheritence