Let's look at an interview question first:
What is the meaning of final? Where can I use it? What are the ways to initialize it?
First we answer this question, and then we explore its why.
1. Final means "final", "immutable", meaning that the value of a property whose cosmetic class cannot be inherited or decorated cannot be changed.
2. Final can either modify the class or modify the properties.
3. The final variable can initialize the value directly, or it can initialize the value in the constructor method, but only one of them is optional.
All right! Now that we know the answer, let's go to one by one to verify it!
1. Direct initialization of attribute values, classes cannot be inherited:
Package Com.smbea.demo;import org.junit.test;/** * Final modifier attribute and initialize directly * This class cannot be inherited * @author Hapday */public final class final DEMO2 {final int num = 9; @Testpublic void Finaltest () {//this.num = 7;//This sentence is commented because it is reported as the final field Finaldemo2.num Canno T be assigned error SYSTEM.OUT.PRINTLN (this.num); Output result: 9}}
2. Initialize the constructor for final variables:
Package com.smbea.demo;/** * Final modified property and initialized with the constructor * @author Hapday */public class Finaldemo {final int num;p ublic finaldem O (int num) {System.out.println ("parameterless constructor"); this.num = num; System.out.println (this.num);} public static void Main (string[] args) {new Finaldemo (8);}}
On the final of Javase