What is significance of second line :
public final class A {}
final A obj1=new A();
If A
is a already immutable, why would one possibly want to make obj1
final? (just to make it stick to a unique memory reference? ).
final
in the first line means that the object is closed for extension...i.e. you can't subclass it.
final
in the second line means you can't reassign the variable.
First, A
is not immutable of you just declare it final
.
Then, final variables cannot be changed. If obj1
is a field this enforces mutability (unlike the final class
).
If it is a local variable it means you can safely use it in anonymous classes (otherwise the compiler can't be sure it won't get change sometimes before/while the anonymous class body is executed)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With