Java中为什么要声明类,为什么要在Java中声明一个不可变的类final?

I read that to make a class immutable in Java, we should do the following,

Do not provide any setters

Mark all fields as private

Make the class final

Why is step 3 required? Why should I mark the class final?

解决方案

If you don't mark the class final, it might be possible for me to suddenly make your seemingly immutable class actually mutable. For example, consider this code:

public class Immutable {

private final int value;

public Immutable(int value) {

this.value = value;

}

public int getValue() {

return value;

}

}

Now, suppose I do the following:

public class Mutable extends Immutable {

private int realValue;

public Mutable(int value) {

super(value);

realValue = value;

}

public int getValue() {

return realValue;

}

public void setValue(int newValue) {

realValue = newValue;

}

public static void main(String[] arg){

Mutable obj = new Mutable(4);

Immutable immObj = (Immutable)obj;

System.out.println(immObj.getValue());

obj.setValue(8);

System.out.println(immObj.getValue());

}

}

Notice that in my Mutable subclass, I've overridden the behavior of getValue to read a new, mutable field declared in my subclass. As a result, your class, which initially looks immutable, really isn't immutable. I can pass this Mutable object wherever an Immutable object is expected, which could do Very Bad Things to code assuming the object is truly immutable. Marking the base class final prevents this from happening.

Hope this helps!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值