final classes and methods

final means "assigned once, decided, not to be changed". It is one keyword in three places, and each place answers a different question: a final field cannot be assigned after its constructor, a final class cannot be extended, and a final method cannot be overridden. The first is about values, the other two are about a design that another programmer is not allowed to change.

final on a field

A final field is assigned once, and the compiler checks every assignment. A field with an initialiser and a constant are the simple cases:

public class FinalFields { private static final int MAX = 3; private final String name; FinalFields(String name) { this.name = name; } public static void main(String[] args) { FinalFields one = new FinalFields("one"); FinalFields two = new FinalFields("two"); System.out.println(one.name); System.out.println(two.name); System.out.println(MAX); } }

javac -Xlint:all FinalFields.java
java FinalFields

one
two
3

Two objects hold two different names, and each name is final: the field is per object and cannot change after the constructor, while the values of two objects are free to differ. MAX is static final, so it belongs to the class and is one value for all objects, which is the constant of lesson 037.

Assigning a field that already has a value is an error the compiler reports at the assignment:

public class Reassign { private final int count = 0; void bump() { count = count + 1; } public static void main(String[] args) { System.out.println(new Reassign().count); } }

javac -Xlint:all Reassign.java

Reassign.java:5: error: cannot assign a value to final variable count
count = count + 1;
^
1 error

The caret points at the assignment, not at the field: what is illegal is the second write, and it is illegal wherever it appears after the constructor.

The blank final

The field name above has no initialiser, and the constructor assigns it. That is a blank final, and it is the normal way to make an object immutable: the value comes from the caller once and never changes. The compiler insists that every constructor assign it, and that no constructor assign it twice, because a final field that some path leaves unset would be a field a reader cannot trust.

A blank final is also the reason a class with a final field cannot use the default constructor once it declares a constructor of its own: the default one assigns nothing, so it would leave the field unset, and the compiler refuses it. Lesson 036 shows the constructor rules that produce the error.

final on a class

A final class cannot be extended. The compiler refuses the subclass at the extends clause and names the class that closed itself:

public class Broken { public static void main(String[] args) { Sub sub = new Sub(); System.out.println(sub); } } final class Base { } class Sub extends Base { }

javac -Xlint:all Broken.java

Broken.java:11: error: cannot inherit from final Base
class Sub extends Base {
^
1 error

java.lang.String is the final class every Java program already uses: no class extends it, so a String method cannot be overridden to return a different text, and the JVM may share and cache strings without asking whether a subclass changed their meaning. The same pattern appears in the JDK wherever a value must behave the same everywhere.

final on a method

A final method cannot be overridden, though the class around it may still be extended. The compiler reports the override in the subclass, and the reason on the second line:

public class FinalMethod { public static void main(String[] args) { Circle circle = new Circle(); System.out.println(circle.area()); } } class Shape { final double area() { return 0; } } class Circle extends Shape { @Override double area() { return 3.14; } }

javac -Xlint:all FinalMethod.java

FinalMethod.java:16: error: area() in Circle cannot override area() in Shape
double area() {
^
overridden method is final
1 error

A final method that is not overridden works like any other. The class below is final, so neither of its methods could be overridden anyway; the final on fahrenheit says the same thing locally, which is what a reader of the method sees first:

public final class Temperature { private final double celsius; public Temperature(double celsius) { this.celsius = celsius; } public double celsius() { return celsius; } public final double fahrenheit() { return celsius * 9 / 5 + 32; } @Override public String toString() { return String.format("%.1f C = %.1f F", celsius, fahrenheit()); } public static void main(String[] args) { Temperature[] week = { new Temperature(0), new Temperature(21.5), new Temperature(-40), }; for (Temperature day : week) { System.out.println(day); } } }

javac -Xlint:all Temperature.java
java Temperature

0.0 C = 32.0 F
21.5 C = 70.7 F
-40.0 C = -40.0 F

The third line is the point where the two scales meet, and the value comes from the same formula as the other two. Nothing in the class can change a temperature after it is built, which is what a value type is for.

Why a designer chooses final

A final class gives up extension, and the designer takes that trade for one of three reasons. A value class such as String, Integer or the Temperature above has an invariant that a subclass could break, and a broken invariant in a value is a bug far from its cause. A class with a security decision inside it cannot let a subclass replace the check with one that always passes. And a class that is not designed for inheritance has no constructor contract, no documentation of what an override may assume, and every subclass that appears constrains its future changes.

That last point is the fragile base class of lesson 062: a method that a superclass calls on itself can be overridden into an inconsistency. final on that method, or on the whole class, removes the possibility instead of documenting it.

A final local variable and a final parameter are not in the same family: they stop a reassignment inside one method, which a reader sees in five lines, and they matter for one real reason: a lambda may capture only a variable that is effectively final, which is lesson 082. Declaring every local final is a style, not a rule; declaring a field final is a decision about the object.

Exercises

  1. Add a second constructor to Temperature that takes Fahrenheit and computes the Celsius value, and keep the field final.
  2. Try to extend String in a file of your own and read the error.
  3. Remove final from Base in Broken.java and give Sub a field, then build and run it.
  4. Make celsius() return a rounded value and explain why the field stays final while the method does not.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How many times may a final field be assigned?

    Answer

    Once, either in its initialiser or in each constructor

    A final field gets its value in the initialiser or in the constructor, and no later assignment compiles.

  2. What is a blank final?

    Answer

    A final field with no initialiser, assigned by every constructor

    The field is declared final and its value comes from the constructor, once.

  3. What does final on a class prevent?

    Answer

    Any class extending it

    A final class cannot be extended; it can still be instantiated and used.

  4. What does this program print? public class Q1 { private final int value = 4; public static void main(String[] args) { Q1 q = new Q1(); System.out.println(q.value); } }

    Answer

    4

    The initialiser assigns the final field once, before the constructor body runs.

  5. What is the first line of the compiler output for this program? public class Q2 { public static void main(String[] args) { A a = new A(); a.value = 2; System.out.println(a.value); } } class A { final int value = 1; }

    Answer

    error: cannot assign a value to final variable value

    The field has an initialiser, so the assignment in main is a second one.

  6. What does this program print? public class Q3 { public static void main(String[] args) { A a = new A("x"); System.out.println(a.name); } } class A { final String name; A(String name) { this.name = name; } }

    Answer

    x

    The blank final is assigned by the constructor with the argument it was given.

  7. What is the first line of the compiler output for this program? public class Q4 { public static void main(String[] args) { System.out.println(new Sub()); } } final class Base { } class Sub extends Base { }

    Answer

    error: cannot inherit from final Base

    A final class cannot be extended, and javac refuses the extends clause.

  8. What does this program print? public class Q5 { public static void main(String[] args) { A a = new A(3); System.out.println(a.twice()); } } final class A { private final int n; A(int n) { this.n = n; } final int twice() { return n * 2; } }

    Answer

    6

    A final class and a final method are perfectly usable; they only refuse extension and override.

  9. Why is java.lang.String final?

    Answer

    Its value must behave the same in every program, and a subclass could break that

    A value class with an invariant is closed so that no subclass can change what the value means.

  10. Which of these does final on a method do?

    Answer

    Forbids an override in a subclass, while the class may still be extended

    The method is closed, not the class; other methods of the class can still be overridden.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev

Banner image