Final is very important keyword in java which can be applied to variable, method or class in java.Once you make a reference final then you are not allowed to change that reference and on doing so compiler will show the error.
Final variables:We can make the variables final in java and after declaring varibale final we cannot modify it later. Java will treat it like a constant variable. Normally we use static with final and we take variable in capital letters to differentiate it from normal variables. Variables in interfaces are always final.So final variables are read only.
for Ex:
public static final NAME="Abhishek";
NAME="Abhi"; //compiler error
Final methods: We can also make our methods final in java. If we declare our method final then we cannot override it. We can make those methods final which we think are complete and will not changed in future. Final methods are faster than non-final methods because they are not required to be resolved during run-time,they are bonded at compile time.
for ex
Final class: We can also make our class final in java.If we will make our class final in java then the class cannot be inherited.
For ex
Advantages:
1) Final keyword improves performance because JVM as well as application can cache the final variables.
2) Final variables can be shared in multi-threading environment without additional synchronization overhead.
3)Final classes, methods and variables can be optimized by JVM which will improve the performance of the application.
Final variables:We can make the variables final in java and after declaring varibale final we cannot modify it later. Java will treat it like a constant variable. Normally we use static with final and we take variable in capital letters to differentiate it from normal variables. Variables in interfaces are always final.So final variables are read only.
for Ex:
public static final NAME="Abhishek";
NAME="Abhi"; //compiler error
for ex
public class MyClass{
public final int getAge(){
return 18;
}
}
public class MyClassOther{
public int getAge(){
return 21; //compilation error
}
}
public final int getAge(){
return 18;
}
}
public class MyClassOther{
public int getAge(){
return 21; //compilation error
}
}
Final class: We can also make our class final in java.If we will make our class final in java then the class cannot be inherited.
For ex
final class MyClass{
//Statements
}
final MyClassOther extends MyClass{ //compilation error
//Statements
}
//Statements
}
final MyClassOther extends MyClass{ //compilation error
//Statements
}
Advantages:
1) Final keyword improves performance because JVM as well as application can cache the final variables.
2) Final variables can be shared in multi-threading environment without additional synchronization overhead.
3)Final classes, methods and variables can be optimized by JVM which will improve the performance of the application.
0 comments:
Post a Comment