final in Java is used for:
Features and nuances:
final variable must be initialized at the declaration or in the constructor;final reference does not allow changing the reference, but the object referenced can be modified (if it is not immutable!);final class (e.g., String, Math) is not possible;final method, even if the class is inheritable.final class A {} // cannot make class B extends A class Parent { final void foo() { } } class Child extends Parent { // void foo() {} // error: cannot override foo } final int COUNT = 10;
Can you change the state of the object that a final variable refers to?
Answer: Yes, if it is not an immutable object. For example:
final List<String> names = new ArrayList<>(); names.add("Vasya"); // This is allowed — the object referenced is modified, but not the reference itself names = new ArrayList<>(); // Compilation error
Story
Story
Story
There was a task to extend an external API built on final classes. Because of them, it turned out to be impossible to make extensions, leading to duplicated logic and maintaining two independent branches of the product, complicating migrations.