Java Final Keyword
Some things, once decided, must not change: your date of birth on a certificate, the rules of a signed contract. Java's final keyword locks things in the same way. It has three meanings depending on where you put it: on a variable it means "assign once", on a method it means "can't be overridden", and on a class it means "can't be extended". The lesson "Constants in Java" introduced the first; this lesson covers all three.
Three Kinds of final
| Where | Means | Example | Compile error if broken |
|---|---|---|---|
| Variable | Assign once | final int MAX_SEATS = 72; | cannot assign a value to final variable |
| Method | Can't be overridden | final long fee() { ... } | cannot override; overridden method is final |
| Class | Can't be extended | final class PanCard { ... } | cannot inherit from final |
final Variables in a Class
public class Pan {
static final class PanCard {
static final int LENGTH = 10;
private final String number;
private final String holder;
PanCard(String number, String holder) {
this.number = number;
this.holder = holder;
}
String masked() {
return "XXXXXX" + number.substring(6, LENGTH);
}
}
public static void main(String[] args) {
PanCard card = new PanCard("ABCDE1234F", "Srihitha Anamaneni");
System.out.println(card.holder + ": " + card.masked());
}
}Srihitha Anamaneni: XXXXXX234FHow it works
- Line 3:
static finalis a constant, one value for the class (see "Blank Final and Static Final Variables"). - Lines 4 and 5:
finalinstance fields must be assigned exactly once, here in the constructor, and can never change afterwards. - Line 2: the class itself is
final, so nobody can create a subclass that changes how a PAN card behaves.
Try it yourself: add a method void rename(String n) { holder = n; }. What does the compiler say?
final Methods and final Classes
These two are about inheritance (see "Inheritance in Java"), so here are the errors you'll meet:
FinalM.java:2: error: show() in C cannot override show() in P
class C extends P { void show() {} }
^
overridden method is final
FinalC.java:2: error: cannot inherit from final P
class C extends P {}
^A final method lets a class keep a rule fixed, such as how a fee is calculated, while still allowing subclasses for other things. A final class stops all subclassing. String, Integer and all the wrapper classes are final, so nobody can create a sneaky subclass of String that behaves differently.
final Is Not Immutable
final on a reference stops reassignment, not changes to the object (see "Constants in Java"):
public class Seats {
public static void main(String[] args) {
final int[] booked = {0, 0, 0};
booked[1] = 1;
System.out.println(java.util.Arrays.toString(booked));
}
}[0, 1, 0]booked = new int[3]; wouldn't compile, but changing the array's contents is fine. An immutable object, like String or the PanCard above, is one with private final fields and no methods that change them (see "How to Create an Immutable Class in Java").
final Parameters and Locals
final also works on parameters and local variables: void book(final String name). It stops accidental reassignment inside the method. Local variables used inside lambdas (covered later in the course) must be effectively final: never reassigned, even without the keyword.
Common Mistakes
Thinking final makes an object read-only. It only fixes the reference.
Leaving a final field unassigned. Every constructor must assign it exactly once (see the next lesson).
Confusing final, finally and finalize. finally is a block in exception handling (covered later in the course); finalize was an old, now deprecated, cleanup method.
Interview Corner
What are the uses of the final keyword?
A final variable can be assigned only once; a final method can't be overridden by subclasses; a final class can't be extended. Final fields are often combined with private access to build immutable classes such as String.
What is the difference between final, finally and finalize?
final is a modifier for variables, methods and classes. finally is a block after try/catch that always runs, used for cleanup. finalize was a method on Object called by the garbage collector before reclaiming an object; it's deprecated for removal and shouldn't be used.
Practice
- Easy: Make a
Studentclass with afinalroll number set in the constructor, and show that it can't be changed later. - Harder: Write a final class
Moneywith private finalrupeesandpaisefields and a methodplus(Money other)that returns a newMoneyinstead of changing either object.
Key Takeaways
Was this tutorial helpful?