Final keyword in java
Final keyword is used to
restrict the user. You cannot change it after you made it final. Java final keyword
is used to stop changing the value, stop method overriding & to stop
inheritance. Final can be
• variables
• methods
• classes
final variables
If you make any variable as
final you cannot change the final value of it it will be a constant.
Ex:
public class Demo {
public int MAX_VAL= 11;
public void myMethod(){
MAX_VAL= 12;
}
public static void main(String[] args) {
Demo demo= new Demo();
demo.myMethod();
}
}
This will give u an compile
error as we have changed the value of the MAX_VAL.
Final methods
Once the method is final you
cannot override it.
Ex:
final classes
If u make the class final you
cannot extend it.
Ex:
Coding example
public class TestRun {
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.p1);
}
}
class Test{
public double p1=3.14;
Test(){
p1=2.14;
}
}
How to avoid
someone changing the p1 ?
We can have
p1 as final. But when you make it as final you will get an error like this.



No comments:
Post a Comment