There many places in java final keyword is more useful.
If you like the above solution . Please share this blog
- final variable and its static binding
- final method
- final class
The value of the final variable cannot be changed once it is initialized.
final int a=5;
a=a++; // compile time error
Once you have declared variable with final keyword, java compiler will identify this as final and replace it with actual value , this is called static time binding. This will improve the your application performance, i.e instead of reading every time from memory, it will replace variable name with its original value. For ex:
final int a=5;
int b=5;
int add= a + b;
int mul=a*b;
int div=a/b;
The above source code will be converted into below code after compilation.
final int a=5;
int b=5;
int add= 5 + b;
int mul=5*b;
int div=5/b;
The java compiler replace the variable 'a' with its original value.
In Real-time application, use final keyword before the variable which is constant and doesn't change its value in entire flow of application, because it will improve the application performance.
2) final method
Final method cannot be overridden in sub class. You can use final keyword before the method, which you don't want to override in subclass. For ex:
Class Animal {
final public void getName() {
System.out.println(" name ");
}
}
Class Cat Animal {
public void getName() { // compile time error
System.out.println(" name ");
}
}
3) final class
Final class cannot be extend in sub class. In java, final keyword is used to create immutable class to avoid modification of those properties in sub class. All wrapper class such as Integer, Float , Double are created using final keyword.
final Class Immutable{
// properties
}
Class Subclass extends Immutable { // compile time error
}
Key points
- if final variable is not initialized, it is called as blank variable and it will be initialized only in constructor.
- static blank final variable will be initialized only in static block.
- if you are using final variable in method arguments, it cannot be changed inside the method.
- constructor cannot be final.
- final method can be inherited but it cannot be override.
- All variable declared inside java interface are implicitly final
Click to Read more Core Java interview questions and answers
If you like the above solution . Please share this blog
No comments:
Post a Comment