final in java

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值