Final Keyword In Java

Final Keyword In Java

Final Keyword In Java

Final Keyword In Java:

In Java, the final keyword is used to declare that a variable, method, or class cannot be modified once it has been initialized. Here are some common uses of the final keyword:

  1. Final variable: A final variable can only be assigned once. Once it is assigned, it cannot be changed. For example:
				
					final int num = 10;
				
			
  1. Final method: A final method cannot be overridden by a subclass. This is often used to prevent the subclass from changing the behavior of the method. For example:
				
					class Parent {
    final void print() {
System.out.println("This is a parent method.");
    }
}

class Child extends Parent {
    void print() { // This will result in a compile-time error
System.out.println("This is a child method.");
    }
}

				
			
  1. Final class: A final class cannot be subclassed. This is often used to prevent the class from being extended and modified. For example:
				
					final class MyClass {
    // ...
}

// This will result in a compile-time error
class MySubclass extends MyClass {
    // ...
}

				
			

Note that using the final keyword can improve the performance of Java programs in some cases, as the compiler can make certain optimizations based on the assumption that the value of a final variable will not change.

Join To Get Our Newsletter
Spread the love