Video in progress
What does final change when it is put on a class, a method and a variable?
A final class can't be inherited from (String). A final method can't be overridden by a child class. A final variable or field gets its value only once; if it is an object, the reference doesn't change, but the inside of the object can.
📖 Answer
public final class Money { ... } // extends Money is an error
class BaseService {
public final void audit() { ... } // overriding in a child is an error
}
final List<String> names = new ArrayList<>();
names.add("Ali"); // allowed: the inside of the object changed
// names = new ArrayList<>(); // error: the reference is fixed
Why it is needed:
- class: it prevents unplanned inheritance. If your class wasn't designed for extension, making it
finalis safer; - method: so that an important algorithm in the parent class (for example the skeleton of a template method) can't be broken by the children;
- field: for writing immutable objects, so the state doesn't change after the constructor.
One catch: final fields also get a special guarantee in the Java Memory Model: once the constructor finishes, other threads see their correct values.
A local variable used inside a lambda must be "effectively final", meaning that even if it isn't written as final, it must never be assigned again.
Sign up to mark studied questions and save your progress.