+ 9
Qus:- What is the final keyword in Java?
6 Respuestas
+ 12
final is a keyword used to make a variable constant.
Like
final float Pi=3.14;
This will declare a constant named Pi which is equal to 3.14.
If you will try to change the value of this constant , you'll get an error
+ 3
final keyword in Java can be used in many context.
final can be:
1. final variable
2. final method
3. final class
1) final variable - to create constant variables
2) final method - to prevent method overloading
3) final class - to prevent inheritance
+ 3
1)final variable:
1. When a variable is declared with a final keyword, it's value cannot be modified.
2. Means by using final keyword, the variable becomes constant.
3. This also means you must initialize a final variable.
4. final variable cannot be inherited.
Example:
class Test
{
public static void main(String args[])
{
final int i =10;
i=30;
}
}
Output:
Error- Cannot assign a value to final variable i
i=30
+ 3
2) final method:
1. A final method cannot be overridden.
2. Which means even the subclass can call the final method of parent class without any issues but it cannot override it.
Example:
final void show()
{
}
+ 3
3) final class:
1. The final class is complete in nature and cannot be subclassed or inherited.
2. Several classes in Java are final like String, Integer and other Wrapper classes.
Example:
final class Exam
{
}
class Test extends Exam
{
public static void main(String args[])
{
Test t1=new Test();
}
}
Output:
Error- Cannot inherit from final class