应该是一个java类'领域永远是最终的?这是一个很好的实践?

时间:2015-04-27 10:03:38

标签: java final

Java类应该是'领域总是最终的?这是一个好习惯吗?

我知道' final'表示原语或对象类型。我的问题是我应该经常(或总是)使用最终字段吗?

e.g。

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>
     */

3 个答案:

答案 0 :(得分:2)

只是一个简短的例子,假设你有一个班级'学生'。 在那里,你有一个字段'birthDate'。

现在,这个领域可能是最终的,因为可以安全地假设,如果你的出生日期是1980年1月20日,那么明年它仍然是那个日期。

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

private String major;

这不应该是最终的。你会让学生无法改变专业,这种情况经常发生。

因此,对于原始类型:在对象的整个应用程序/生命周期中,值是否永远不会改变,然后它可以(但不一定)是最终的。

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

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

答案 1 :(得分:0)

不,最终意味着您无法在实例化后更改字段的值。当然有些值你宁愿永远不会改变,比如Pi的值,但大部分时间你都不会想要

答案 2 :(得分:0)

作为其他答案的补充:

如果您将对象的所有字段设为final并确保引用的对象具有相同的限制,则可以创建具有自身优势的Immutable Object(即线程安全,没有side effects)和缺点(您必须使用copy on write,没有副作用。)

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