Keyword explanation in Java
1. Final
Final keyword modifier member variable
You can define a member variable as final, but such a member variable must be initialized when constructing an object. That is to say, after each constructor is executed, the values of these member variables must be set and cannot be modified in subsequent operations.
For example:
Package COM. dingji. java. test. bean; public class test {final string mname; public test (string name) {// The final variable must be initialized in the constructor; otherwise, the mname cannot be compiled ;}}
What if it is a static final variable? The constructor cannot be initialized. What should I do? We can use static blocks for initialization.
For example:
package com.dingji.java.test.bean;public class Test {static final String mName;static {mName = "dingji";}}
Let's take a look at this piece of code:
Package COM. dingji. java. test. bean; import Java. util. date; public class test {final date mdate; public test () {mdate = new date ();} public void changedate (long milliseconds) {// you can change the mdate object of mdate. settime (milliseconds );}}
We can see from the above that we can change the mdate object, that is, the mdate object cannot be changed, that is, the object reference, and the object can be changed, however, after the object is constructed, mdate points to the object and remains unchanged.
Final keyword modifier class and Method
Sometimes, you may want to prevent people from using a class to define a subclass. classes that cannot be extended are called final classes, if the final modifier is used to define a class, it indicates that the class is a final class.
The methods in the class can also be declared as the final type. If this is done, the subclass will not be able to override this method (all methods in the final class will automatically become the final method ).