You always think you will, in fact, you just smattering.
Final keyword Overview
The final keyword can be used to declare properties, methods, parameters, and classes, respectively, to indicate that the property is not mutable, that methods are not overwritten, that the parameters are immutable, and that the class cannot inherit.
Let's take a look at the use of it separately.
The final keyword is a relatively simple point of knowledge, so this article I write more comfortable, you look more comfortable. Because, very simple ~
Final Property
The properties that are final decorated are immutable. This immutable attribute, which we can call "constant". There are generally two representations of this constant. First look at the following code:
publicclass FinalAttribute { private"chengfan"; publicvoidtest(){ //attribute_a = "zhangbingxiao"; 不可以这样写 }}
This is the most basic final attribute, initialized at the time of definition, and the compile time value is determined and cannot be modified.
Let's look at one more:
publicclass FinalAttributeB { private final String attribute_b; publicFinalAttributeB(String attribute_b){ this.attribute_b = attribute_b; } publicvoidtest(){ //attribute_b = "zhangbingxiao"; } publicvoidtest(String attribute_b){ //this.attribute_b = attribute_b; }}
This final property cannot determine the property value during compilation, only when it is run (through the constructor initialization property). Similarly, once an attribute is initialized, it cannot be changed, so the test method below cannot modify the final property.
In the previous article, we talked about blocks of code, so can we use blocks of code to initialize the final property? The answer is of course possible:
publicclass FinalAttributeB { private final String attribute_b; { "zhangbingxiao"; } static { //attribute_b = "zhangbingxiao"; }// public FinalAttributeB(String attribute_b){// this.attribute_b = attribute_b;// }}
It is also possible to initialize the final property by constructing a code block, but you can no longer use the constructor to initialize it, because the construction code block is executed before the constructor. The final attribute can only and must be initialized once.
You may have found that I wrote a static block of code, but commented out. Yes, because static code blocks can only initialize static properties, we'll discuss it at the end of the article.
This is not initialized at the time of definition, but is initialized with a constructor, also known as a blank final variable. It provides greater flexibility in the use of final, so that the final data members in a class can be implemented differently depending on the object, but with the same characteristics that keep them constant.
Is there any other way to compile-time initialization besides the constructor? Of course there are, for example, you use random to initialize:
privatefinalintnew Random().nextInt();
This way you only know what the property value is when you run it.
What we've just studied is the basic data type, so what about the reference data type? Look directly at the code:
Public class Finalattributec { Private FinalPerson person =NewPerson ("Zhangbingxiao"); Public void Change() {Person.setname ("Chengfan"); System.out.println (Person.getname ()); }//public void Change (person p) { //this.person = p; //} Public Static void Main(string[] args) {NewFinalattributec (). change (); }}//Result: Chengfan
Commented out code is the code that will error, that is, reference type person can not be modified. As you can see from the results, the properties inside the person object have been changed.
So, for reference types, the reference itself cannot be changed, but the object that the reference points to can be changed.
The reference exists in the stack, and the object exists in the heap. The referenced value is the address of the object in the heap. In essence, the final decoration is a reference, not an object. So the quoted address doesn't change, and it doesn't matter much to the object.
To give a simple example, a person is an object, he will wear tops, trousers, shoes, these things people this object's properties. And the person's name is quoted. When your life is down, the name is ok (quote OK), you can change clothes casually, but your name or that.
I'll give an example, don't contradicting with me. What can go to change the name, the duplicate of what. It's good that you understand the final reference type.
Final Method
When a method is declared final, the method cannot be overridden by any subclasses, and this class can be overloaded, but subclasses can use this method.
Public class finalmethod { Public Final voidTest () {} Public voidTestinti) {}} class Test extends finalmethod{ //public void Test () {} cannot be overridden@Override Public voidTestinti) {Super. Test (i); } Public voidTestintIintj) {}}
The method that is final modified cannot be overridden. However, the overloads of this class and the override of overloaded functions are not affected.
There is a mechanism called inline that, when invoking a method that is declared final, inserts the method body directly into the call, rather than making a normal method call (similar to a C + + inline), which helps to improve the efficiency of the program.
However, if the method is too large, you may not see any performance gains from inline calls. In the recent Java release, these optimizations do not need to be made using the final method.
Final Parameter
When a method's formal parameter is final modified, this parameter cannot be modified within the method.
publicclass FinalParam { publicvoidtest(finalint a ){ //a = 10; 值不可以被修改 } publicvoidtest(final Person p){ //p = new Person("zhangbingxiao"); 引用本身不可以被修改 p.setName("zhangbingxiao"); //引用所指向的对象可以被修改 }}
The modification rules for reference data types are the same as the final property.
Final modifier parameters are very useful in internal classes, in order to maintain parameter consistency in an anonymous inner class, the formal parameter must be final if the formal parameter of the method is to be used inside the inner class.
This knowledge will be discussed in detail when explaining the inner class, and the interested can be studied first.
final modifier local variable
The final modifier can only be initialized (assigned) once, not immediately, when the local variable is modified.
publicclass StaticPartAttr { publicvoidtest(){ finalint a ; finalint2; 3; //a = 4; 报错 //b = 5; 报错 }}
A local variable that is final modified can only be assigned once.
You can also never initialize, but do not assign values, what is the use of defining this variable?
Final Class
A final modified class cannot be inherited, and all methods cannot be rewritten (nonsense, not inherited, which overrides). However, this does not mean that the properties inside the class are not modifiable, unless the property is also final decorated. This is a lot of applications in the JDK, such as our well-known String,integer and other classes are final modified.
The final class has many benefits, such as that their objects are read-only, can be shared securely in a multithreaded environment, without additional synchronization overhead, and so on.
How do I write an immutable class?
- Declares a class as final, so it cannot be inherited
- Declare all members private so that you do not allow direct access to those Members
- Do not provide setter methods for variables
- Declare all mutable members as final so that they can be assigned only once
- Initialize all members through the constructor for deep copy
- In the getter method, do not directly return the object itself, but instead clone the object and return a copy of the object
For details, drop a link and run quickly.
It is important to note that a class cannot be both abstract and final decorated. Because the final class cannot be inherited, the abstract class needs to be inherited. For abstract classes, we will explain them in detail in the next article.
Final and Static
When final and static are used at the same time, the "global constants" We are familiar with appear: a property that can be used everywhere and cannot be changed, such as the MATH.PI,MATH.E we know.
Above, we talked about the problem of initializing the final variable with a static block of code.
Public class finalstatic { Private Final Static DoublePI =3.14;Private Final Static DoubleEPrivate Final Static DoubleC//There will be an error Static{E =2.71; } Public finalstatic(Doublec) {c = c;//pi = C; There will be an error .}}
For static final variables, we can initialize directly, or use static blocks of code. You cannot use constructors or construct blocks of code.
Because static requires a value to be determined during compilation, it is then put into the static zone. While constructors and construction code blocks occur during run time. So there is no blank static final.
Final and private
All private methods in a class are implicitly specified as final, and because the private method cannot be overridden, you can add the final modifier to the private method without adding any additional meaning.
Summary
Important points of knowledge about final
- The final keyword can be used for member variables, local variables, methods, and classes.
- The final member variable must be initialized at the time of declaration or initialized in the constructor, or a compilation error will be reported.
- You cannot assign a value to the final variable again.
- A local variable must be assigned a value at the time of declaration.
- All variables in an anonymous class must be final variables.
- The final method cannot be overridden.
- The final class cannot be inherited.
- All the variables declared in the interface are final.
- The final and abstract two keywords are anti-related, and the final class cannot be abstract.
- The final method is bound during the compile phase, called static binding.
- No final variables, called blank final variable, are initialized at the time of declaration, and they must be initialized in the constructor or in a code block.
- Declaring classes, methods, and variables as final can improve performance, so that the JVM has an opportunity to estimate and then optimize.
- According to the Java Code convention, the final variable is constant, and the pass is often capitalized.
This concludes the content of this article. If the article is wrong or you have a better understanding of the way, please contact me in time ~ Welcome to point out the error, compare I am also a learning person rather than the great God.
Reprint please indicate the source
This address: http://blog.csdn.net/qq_31655965/article/details/54800523
After reading, order a praise Bai ~
Re-understanding Java (vii)----final keywords