Final can be used to modify classes, variables, and methods.
Classes modified by final will not be inherited;
Variables modified by final fall into two categories:
-
If it is a variable of a primitive data type, the value of the variable cannot be changed. (Commonly known as constant)
-
If a variable refers to a data type, the reference to which the variable refers cannot be changed, but the content of the referenced object can be changed.
public class Test {
// Final modified member variables can be initialized directly by assignment, or they can be initialized in the constructor
// final Decorates base datatype variables whose values cannot be changed
public final int element = 10;
// final Modifies a reference datatype variable, the content can be changed, but the reference cannot be changed
public final List<Integer> list = new ArrayList<Integer>();
public void test(int element) {
// this.element = element;list.add(element); }}Copy the code
Methods modified by final cannot be overridden by subclasses.
It is very important to make sure that everything is final.