In Java, the final
keyword is used to restrict the modification of a variable, method, or class. Once a variable, method, or class is declared as final
, its value or implementation cannot be changed.
Here are some common uses of the final
keyword in Java:
- Final variables:
A final variable is a constant whose value cannot be changed once it is assigned. It can be assigned a value only once, either at the time of declaration or in a constructor. For example:
final int x = 10;
- Final methods:
A final method is a method that cannot be overridden by a subclass. Once a method is declared as final in a superclass, its implementation cannot be changed in any subclass. For example:
public class Parent {
public final void method() {
// method code here
}
}
public class Child extends Parent {
// cannot override the Parent method
}
- Final classes:
A final class is a class that cannot be subclassed. Once a class is declared as final, it cannot be extended by any subclass. For example:
public final class MyClass {
// class code here
}
public class MySubclass extends MyClass {
// error: cannot extend final class
}
In addition to the above uses, the final
keyword is also used in Java to declare constants, as well as to prevent reference variables from being reassigned.