创建一个没有final字段的不可变对象? [英] Creating an immutable object without final fields?

查看:136
本文介绍了创建一个没有final字段的不可变对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以创建一个不可变对象,而不是所有字段都是最终的吗?

Can we create an immutable object without having all fields final?

如果可能的话,几个例子会有所帮助。

If possible a couple of examples would be helpful.

推荐答案

声明所有字段为私有且仅定义getter:

Declare all fields private and only define getters:

public final class Private{
    private int a;
    private int b;

    public int getA(){return this.a;}
    public int getB(){return this.b;}
}

引用@Jon Skeet的评论,最终的类修饰符适用于:

citing @Jon Skeet's comment, final class modifier is useful for:


虽然只是Private的实例是不可变的,但
子类的实例可能是可变的。所以接收类型为
Private的引用的代码不能依赖它是不可变的而不检查它是否只是私有的
实例。

While an instance of just Private is immutable, an instance of a subclass may well be mutable. So code receiving a reference of type Private can't rely on it being immutable without checking that it's an instance of just Private.

因此,如果你想确定你所指的实例是不可变的,你应该也使用final final modifier。

So if you want to be sure the instance you are referring to is immutable you should use also final class modifier.

这篇关于创建一个没有final字段的不可变对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆