final means, this value won't be changed here after.

final is one of the most under-used features of Java. Whenever you compute a value and you know it will never be changed subsequently put a final on it. Why?

• final lets other programmers (or you reviewing your code years later) know they don't have to worry about the value being changed anywhere else.

• final warns won't let you or someone else inadvertently change the value somewhere else in the code, often by setting it to null. final helps prevent or flush out bugs. You can always remove it later.

• final helps the compiler generate faster code.

The term final is used in a number of contexts. static final variables are close to constants in other languages. final classes may not be subclassed. final methods may not be overridden. On methods private implies final, but on variables does not. Marking things final has two purposes: efficiency and safety. The compiler can perform various optimisations knowing the value cannot change. Hotspot and optimising compilers now do this anyway, whether or not you declare methods final, so using final purely for efficiency is no longer recommended. The compiler can also check to ensure you do not inadvertently attempt to change the value after computing its value once where it is defined.

A little known feature of Java is blank finals. You can declare member variables final, but not declare a value. This forces all constructors to initialise the blank final variables.

You can have both final instance and final static variables. final statics are more common. When you know the value of a constant at compile time you might as well make it static. It takes up less room, just one copy per class instead of one copy per object. It is also faster to access a static constant than an instance constant. However, if you don't know the value of the constant until instantiation time, you have to make it an instance constant.

If you have a final reference to an object or array, it does not stop you from changing the fields in the object or elements of the array. It just stops you from pointing that variable to a different object or array. If you want to protect the object, you must make it immutable.




您的电子邮箱地址不会被公开。 必填项已用*标注