final keyword in java
The ” final
” keyword can be applied for variables,methods and classes.
final variable:
if a variable is marked as final, its reference can not be changed once initialized.
Example:
final int x=10;
Now variable “x” is called final
variable and its value 10 can not be changed further and doing so will give compile time error.
the following code attempts to assign another value to it, will fail:
x=15;
final method:
If a method is marked as final, that means it can not be overridden in subclass.
Example:
- class Parent {
- final void display() {
- System.out.println("Hello");
- }
- }
- class Child extends Parent {
- void display() {System.out.println("Hi");
- // compile time error as final methods can't be overridden
- }
- }
class Parent { final void display() { System.out.println("Hello"); } } class Child extends Parent { void display() {System.out.println("Hi"); // compile time error as final methods can't be overridden } }
final class:
If a class is marked as final, it can not be sub classed or it can not be inherited by another class.
Example:
- final class Parent {
- }
final class Parent { }
then below code will not compile:
- class Child extends Parent {
- // compile time error as final class can't be inherited
- }
class Child extends Parent { // compile time error as final class can't be inherited }
Note:
A class can never be bothabstract
and final
.
abstract
means the class must be extended,while final
means it can not be, so it’s a kind of deadlock behavior if we make it as both abstract and final and hence Java does not allow such behavior.
A method can never be both abstract
and final
.
abstract
means the method must be overridden, while final
means it can not be, so its kind of deadlock behaviour if we make it as both abstract and final and hence Java does not allow such behavior.
"
So Class and method can not be both abstract and final together but it can become abstract or final independently. "