Final: A common way to modify a class (the class cannot be inherited) (a method cannot be overridden) variable (the variable cannot be re-assigned, which is actually a constant) constant: A: Literal constants, such as "Hello",10.trueB: Custom constants, such asFinal intx = 10;1, the final modifier base type, is that the value cannot change the final decorated reference type, and the address value cannot be changed for example:classstudent{intAge = 10;}classfinaltest{ Public Static voidMain (string[] args) {Final intx = 10; X= 100;//error, unable to assign value for final variable xSystem.out.println (x); FinalStudent SS =NewStudent (); Ss.age= 100; System.out.println (ss.age)//ok,100//re-allocating memory spaceSS =NewStudent ();//error, unable to reassign value }}
2, the initialization time of the final modified variable
A: A final modified variable can only be assigned once
B: Before the construction method is finished (non-static constants)
Example:
Class demo{
Final int x = 10;
{Final int y = 10;}
final int z;
Public Demo () {
x = 100; Error
y = 100; Error, constructing code block takes precedence over construction method
z = 100; No error, because at first it's just a declaration, no assignment.
}
}
Java Foundation--final--008