In the process of programming, we always encounter the final keyword, then we have to final how to understand, the following is a little superficial understanding of me, and you share.
package zy.pro.jbd.demo;
public class FinalDemo {
final int numInt1=16;
final String str="zy";
final String str1;
Note: STR1 is not initialized here, you must initialize it in the constructor, or you will have to make an error. In other words, the final variable must be initialized.
public FinalDemo() {
str1="zy";
}
public static void main(String[] args){
System.out.println("-------------------------------------------------");
}
public void executeFinalTest(){
}
private void testFinalInt(){
numInt1+=1;
Above, we define NUMINT1 as final variable, and an error will occur at the time: cannot assign a final value to final variable numInt1 in line 24
Thus, if a variable of a basic type is defined as final, then this variable will no longer be changed.
System.out.println(numInt1);
}
private void testFinalString(){
str=str+"aaaaa";
The same error is also shown here.
System.out.println(str);
}
}
Let's make one more test:
(1) First create a class: A.java
package zy.pro.jbd.testbase;
public class A {
int t=10;
public A() {
}
public void setT(int t){
this.t=t;
}
public int getT(){
return this.t;
}
}
(2) write the following test code
final A a = new A();
public void testFinalObject() {
a.setT(29);
System.out.println("t: " + a.getT());
}
The results of the test output are:
T:29