java class' 字段应该始终是最终字段吗?这是一个好习惯吗?

should a java class' fields always be final?it 's a good pratice?

Java class' 字段应该总是最终的吗?这是一个好习惯吗?

我知道 'final' 对于原始类型或对象类型意味着什么。我的问题是我应该经常(或总是)使用带有 final 的字段吗?

例如

public class MemoryUsage {
    private final long init;
    private final long used;
    private final long committed;
    private final long max;

    /**
     * Constructs a <tt>MemoryUsage</tt> object.
     *
     * @param init      the initial amount of memory in bytes that
     *                  the Java virtual machine allocates;
     *                  or <tt>-1</tt> if undefined.
     * @param used      the amount of used memory in bytes.
     * @param committed the amount of committed memory in bytes.
     * @param max       the maximum amount of memory in bytes that
     *                  can be used; or <tt>-1</tt> if undefined.
     *
     * @throws IllegalArgumentException if
     * <ul>
     * <li> the value of <tt>init</tt> or <tt>max</tt> is negative
     *      but not <tt>-1</tt>; or</li>
     * <li> the value of <tt>used</tt> or <tt>committed</tt> is negative;
     *      or</li>
     * <li> <tt>used</tt> is greater than the value of <tt>committed</tt>;
     *      or</li>
     * <li> <tt>committed</tt> is greater than the value of <tt>max</tt> 
     *      <tt>max</tt> if defined.</li>
     * </ul>
     */

只是一个简短的例子,假设您有一个 class 'Student'。 在那里,你有一个字段 'birthDate'.

现在,这个字段可以是最终字段,因为可以安全地假设,如果昨天您的出生日期是 1980 年 1 月 20 日,那么明年仍然是那个日期。

但是,如果你有一个字段:

private String major;

这应该不是最终的。你会让学生无法转专业,这是经常发生的事情。

因此,对于基本类型:在对象的 application/lifetime 的整个流程中,值是否永远不会改变,那么它可以(但不一定)是最终的。

如果它是一个对象:如果不可能重新引用它,它可以是最终的。

但是,没有。远非所有变量都应该是最终的。

不,Final 意味着您不能在实例化后更改字段的值。当然有些值你宁愿永远不要改变,比如 Pi 的值,但大多数时候你不希望那样

作为对其他答案的补充:

如果您将一个对象的所有字段都设置为 final 并确保引用的对象具有与您创建 Immutable Object with its own benefits (i.e. thread safety, no side effects 相同的限制)和缺点(您必须使用 copy on write,没有副作用) .

此设计的一个示例是 java.time 包。