final in java

来源:互联网 发布:苹果微信一键转发软件 编辑:程序博客网 时间:2024/05/14 04:13

The final keyword can be applied to classes, methods, or fields.
When applied to a class, it means that the class cannot be subclassed.
When applied to a method, it means that the method cannot be overridden by a subclass.
When applied to a field, it means that the field’s value must be assigned exactly once in each constructor and can never change after that.

What is final in Java? Final variable , Method and Class Example
浅析Java中的final关键字
深入理解Java中的final关键字
Java theory and practice: Is that your final answer?

final applied to Class or method:
Declaring a class or method as final is not to enhance performance. The most common is that final guarantees that classes intended to be immutable stay immutable. With final classes and methods you should always ask yourself: Do you really need to use final?

final applied to variable:
Java allows marking variables (fields / locals / parameters) as final, to prevent re-assigning into them. These variables are read-only. With final fields, you should ask yourself the opposite question – does this field really need to be mutable? Declaring a final field helps the optimizer make better optimization decisions, because if the compiler knows the field’s value will not change, it can safely cache the value in a register. final fields also provide an extra level of safety by having the compiler enforce that a field is read-only.

PMD Optimization Rules:
A local variable assigned only once can be declared final.
A method argument that is never assigned can be declared final.

Why declare final variables inside methods
Excessive use“final” keyword in Java
In Java, should I use “final” for parameters and locals even when I don’t have to?
How final keyword works
String and final
What would truly happen if java.lang.String weren’t final?
Why is string final in java
Why class String definition has final modifier

0 0
原创粉丝点击