Java final keyword
In java, the final is a keyword and it is used with the following things.
- With variable (to create constant)
- With method (to avoid method overriding)
- With class (to avoid inheritance)
Let's look at each of the above.
final with variables
When a variable defined with the final keyword, it becomes a constant, and it does not allow us to modify the value. The variable defined with the final keyword allows only a one-time assignment, once a value assigned to it, never allows us to change it again.
Let's look at the following example java code.
public class FinalVariableExample {
public static void main(String[] args) {
final int a = 10;
System.out.println("a = " + a);
a = 100; // Can't be modified
}
}
When we run this code, it produce the following output.
final with methods
When a method defined with the final keyword, it does not allow it to override. The final method extends to the child class, but the child class can not override or re-define it. It must be used as it has implemented in the parent class.
Let's look at the following example java code.
class ParentClass{
int num = 10;
final void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}
public class FinalKeywordExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
obj.showData();
}
}
When we run this code, it produce the following output.
final with class
When a class defined with final keyword, it can not be extended by any other class.
Let's look at the following example java code.
final class ParentClass{
int num = 10;
void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
class ChildClass extends ParentClass{
}
public class FinalKeywordExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
}
}
When we run this code, it produce the following output.