Final Keyword in Java
0% completed
Final Keyword in java:
Can Assign?
Can Modify?
Can Override?
Can Inherit?
Basics Of Java
Final Keyword in java:

 

Final Keyword in Java

footer line

Final Keyword

 

In Java, the final keyword is only applicable to methods, variables, and classes. It is primarily used to control the user's ability to use variables, methods, and classes.

 

 

final variable

 

In Java, a variable is a final variable if it is declared with the final keyword. The final variable's value is assigned only once. We cannot modify the value of the final variable after it has been assigned. If we attempt to reassign the value, we will get a compile-time error.

 

Example:

 

public class FinalVariableExample {

	// Final variable.
	final int val = 50;

	void show() {

        // Trying to change the value of the final variable, 'val'
		val = 100;

		System.out.println(val);
	}

	public static void main(String args[]) {

		FinalVariableExample obj = new FinalVariableExample();
		obj.show();
        
	}

}


Output:

 

FinalVariableExample.java:9: error: cannot assign a value to final variable val
                val = 100;
                ^
1 error

 

 

final method

 

When a method is declared with the final keyword, it is referred to as the final method. The characteristic of the final method is that the child class cannot override it.

If we do not want our method's implementation to be changed, we should make it final.

 

Example:

 

class FinalMethodExample {

	// Final method
	final void show() {
		System.out.println("Inside FinalMethodExample Class Method");
	}

}

public class CodingNinjas extends FinalMethodExample {

	// Trying to override the final method, 'show'
	void show() {
		System.out.println("Inside Coding Ninjas Class Method");
	}
	
	public static void main(String args[]) {

		CodingNinjas obj = new CodingNinjas();
		obj.show();

	}

}

 

Output:

 

CodingNinjas.java:13: error: show() in CodingNinjas cannot override show() in FinalMethodExample
        void show() {
             ^
  overridden method is final
1 error

 

 

final class

 

When a class is declared with the final keyword, it is referred to as the final class. The special thing about a final class is that it cannot be extended.

Therefore, to prevent a class from being inherited, we should use a final class.

 

Example:

 

// Final Class
final class FinalClassExample {
	/*
	Methods and Data Members
	 */
}

// Trying to extend the final class, 'FinalClassExample'
public class CodingNinjas extends FinalClassExample {

	void show() {
		System.out.println("Inside Coding Ninjas Class Method");
	}

	public static void main(String args[]) {

		CodingNinjas obj = new CodingNinjas();
		obj.show();

	}

}

 

Output:

 

CodingNinjas.java:9: error: cannot inherit from final FinalClassExample
public class CodingNinjas extends FinalClassExample {
                                  ^
1 error