Pen questions related to final keywords are also mandatory. In addition, final has a wide range of practical applications. If you do not have enough knowledge about it during code design, it may be difficult to troubleshoot exceptions related to it.
Final's theoretical knowledge is as follows:
Final type member variable initialization value:
1. assign values directly during Declaration
2. assign values to constructor methods. If a class contains multiple constructor methods, you must ensure that the final type variables must be initialized in each constructor.
3. Static final member variables must be assigned a value during declaration and cannot be assigned a value in the constructor.
4. final member variables indicate that the reference cannot be changed, that is, the reference of the variable cannot point to other objects, but the content of the object can be changed, for example, stringbuffer can change the content of this object through append, remove, and so on.
5. the modifier of a class cannot be abstract or final at the same time.
Abstract classes need to be used through subclass inheritance, while final is non-inherited and conflict with each other.
6. Why do publicfinal-type member variables usually contain static variables?
Because it can save memory and static type, all objects have only one variable. If it is not static, each object must have a variable, which cannot be changed.
Code example: (you can release the commented-out code and check the effect)
/** * author Ding Chengyun * 2014-2-23 */package test;/** * @author Ding Chengyun * 2014-2-23 */public class FinalTest {private static final int a = 1;//private final int a = 1;private String name;private final StringBuffer sb = new StringBuffer();private final Fi fi= new Fi();private final Integer i = new Integer(3);public FinalTest() {//a = 3;}public FinalTest(String name) {//a = 3;this.name = name;}public static void main(String[] args) {FinalTest ft = new FinalTest();FinalTest f = new FinalTest("hello");System.out.println(ft.a);System.out.println(f.a);ft.sb.append("aa");ft.fi.str = "abc";System.out.println(ft.fi.str);}}class Fi {public String str;}