Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why declare a reference to an instance of a final class as being final?

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? ).

like image 317
David Prun Avatar asked Jul 06 '11 17:07

David Prun


2 Answers

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.

like image 152
highlycaffeinated Avatar answered Oct 01 '22 00:10

highlycaffeinated


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)

like image 43
Bozho Avatar answered Sep 30 '22 23:09

Bozho