The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
- variable
- method
- class
- final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).public class FinalVariableExample { public static void main(String[] args) { final int MAX_VALUE = 100; // Attempting to change the value will result in a compilation error // MAX_VALUE = 200; // Error: cannot assign a value to final variable System.out.println("Maximum value: " + MAX_VALUE); }}
public class FinalVariableExample {
public static void main(String[] args) {
final int MAX_VALUE = 100;
// Attempting to change the value will result in a compilation error
// MAX_VALUE = 200; // Error: cannot assign a value to final variable
System.out.println("Maximum value: " + MAX_VALUE);
}
}
- final method
If you make any method as final, you cannot override it.
class Parent {
final void myMethod() {
System.out.println("This is a final method in the Parent class.");
}
}
class Child extends Parent {
// Attempting to override the final method will result in a compilation error
// void myMethod() {} // Error: myMethod() in Child cannot override final
// method in Parent
}
public class FinalMethodExample {
public static void main(String[] args) {
Child child = new Child();
child.myMethod(); // Calls the method from the Parent class
}
}
- final class
If you make any class as final, you cannot extend it.
final class FinalClass {
// Class implementation
}
// Attempting to create a subclass will result in a compilation error
// class SubClass extends FinalClass {} // Error: cannot inherit
// from final FinalClass
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.
public class BlankFinalVariableExample {
// Blank final variable (instance variable)
final int instanceVariable;
// Blank final static variable
static final int staticVariable;
// Static block to initialize the static variable
static {
staticVariable = 50;
}
// Constructor to initialize the instance variable
public BlankFinalVariableExample(int value) {
instanceVariable = value;
}
public static void main(String[] args) {
BlankFinalVariableExample obj = new BlankFinalVariableExample(10);
System.out.println("Instance Variable: " + obj.instanceVariable);
System.out.println("Static Variable: " + staticVariable);
}
}
Комментариев нет:
Отправить комментарий