简体   繁体   中英

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

final in the first line means that the object is closed for extension...ie 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM