Final Key Word in Java


 

Final Key Word in Java

In this tutorial you will learn about final key word of java and its different uses with fields, methods, classes

In this tutorial you will learn about final key word of java and its different uses with fields, methods, classes

Final key word in java

In java final is a key word used in several different contexts. It is used before a variable, method, and classes so that they cannot be changed latter.

Final Variables/fields

A final variable can only once assigned a value. This value cannot be changed latter. If final variable used in class then it must assigned a value in class constructor. Attempting to change the value of final variable/field will generate error.

Example-

public class FinalField {

	public final int fistField;
	public final int secondField;

	FinalField(int first, int second) {
		fistField = first;
		secondField = second;
	}

	 [...]
}
Final Method
A final method cannot be overridden by sub class. To declare a final method put the final after the access pacifier and before the return type.
Eaxample-
public class FinalField {
			public final int addNumber(){
			final int result; 
			// Your code
			return result;
			}
		}

Final Class

A class declared final cannot be sub classed. Other classes cannot extend final class. It provides some benefit to security and thread safety.

Example-

final class MyFinalClass {
	public final int fistField;
	public final int secondField;

	MyFinalClass(int first, int second) {
		fistField = first;
		secondField = second;
	}
}

Blank Final

A blank final is a final variable introduced in java 1.1, its declaration lacks an initializer. A blank final can only be assigned to once and it must be definitely unassigned when assignment occurs. Java compiler runs a flow analysis to ensure every assignment to blank final variable. This variable must be unassigned before assignment otherwise the compiler will give an error message.

Example-

private final int j; // Declaring Blank final
	j = 5; // Initialize blank final

Ads