Final keyword in Java

A final keyword in Java can be applied on variables, methods and classes to prevent further changes to their value or structure.

Final Variable

You can prevent changing the value of a variable by declaring the variable as final. Java will not allow you to initialize the final variable after its first initialization.

package com.techstackjournal.finalexample;

public class MyNumber {
	private final double num;
	
	public MyNumber(double num){
		this.num = num;
	}
	
	public void setNum(double num) {
		this.num = num;
	}
	
}
package com.techstackjournal.finalexample;

public class MyNumberApp {

	public static void main(String[] args) {
		MyNumber num = new MyNumber(10);
		num.setNum(20);
	}

}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The final field MyNumber.num cannot be assigned

	at com.techstackjournal.finalexample.MyNumber.setNum(MyNumber.java:11)
	at com.techstackjournal.finalexample.MyNumberApp.main(MyNumberApp.java:7)

Final Method

Declaring a method as final will prevent all of its sub-classes from override the method.

package com.techstackjournal.finalmethod;

public class Alpha {

	public final void displayAlpha() {
		System.out.println("Alpha Method");
	}

}
package com.techstackjournal.finalmethod;

public class Beta extends Alpha {

	public void displayAlpha() {
		System.out.println("Alpha Method Updated");
	}

}

Beta class gets a compilation error as follows:

com\techstackjournal\finalmethod\Beta.java:5: error: displayAlpha() in Beta cannot override displayAlpha() in Alpha
        public void displayAlpha() {
                    ^
  overridden method is final
1 error

Early Binding (vs Late Binding)

Java usually binds the methods at runtime (late binding), but when we declare a method as final, Java compiler can inline the bytecode of that final method within the calling method itself as it knows that this method will never be overridden by some other version. This can improve the performance as compiler can skip the overhead of determining and calling methods at runtime.

Final Class

Declaring a class as final will prevent any class from inheriting from this class.

package com.techstackjournal.finalclass;

public final class Alpha {

	public void displayAlpha() {
		System.out.println("Alpha Method");
	}

}
package com.techstackjournal.finalclass;

public class Beta extends Alpha {

	public void displayAlpha() {
		System.out.println("Alpha Method");
	}

}
com\techstackjournal\finalclass\Beta.java:3: error: cannot inherit from final Alpha
public class Beta extends Alpha {
                          ^
1 error

When do we declare a class final in Java?

We declare a class as final when we want to prevent others to inherit our class to establish a parent-child relationship using extends keyword. However, they can very well instantiate it wherever they want, but they just can’t inherit it.