java:关于不可变和final的问题(java : Question regarding immutable and final)

编程入门 行业动态 更新时间:2024-10-23 07:37:11
java:关于不可变和final的问题(java : Question regarding immutable and final)

我正在阅读Effective Java这本书。

在最小化可变性的项目中,Joshua Bloch谈到让一个类不可变。

不要提供任何修改对象状态的方法 - 这很好。

确保课程无法扩展。 - 我们真的需要这样做吗?

使所有领域最终 - 我们真的需要这样做吗?

例如,让我们假设我有一个不可变的类,

class A{ private int a; public A(int a){ this.a =a ; } public int getA(){ return a; } }

一个从A延伸出来的阶级如何能够妥协A的不变性?

I am reading the book Effective Java.

In an item Minimize Mutability , Joshua Bloch talks about making a class immutable.

Don’t provide any methods that modify the object’s state -- this is fine.

Ensure that the class can’t be extended. - Do we really need to do this?

Make all fields final - Do we really need to do this?

For example let's assume I have an immutable class,

class A{ private int a; public A(int a){ this.a =a ; } public int getA(){ return a; } }

How can a class which extends from A , compromise A's immutability ?

最满意答案

喜欢这个:

public class B extends A { private int b; public B() { super(0); } @Override public int getA() { return b++; } }

从技术上讲,你并没有修改从A继承的字段,但是在一个不可变的对象中,同一个getter的重复调用当然期望产生相同的数字,这在这里不是这种情况。

当然,如果你坚持规则1,你不允许创建这个覆盖。 但是,你不能确定其他人会遵守这个规则。 如果其中一个方法将A作为参数并对其调用getA() ,则其他人可以像上面那样创建类B并将其实例传递给您的方法; 那么,你的方法会在不知道的情况下修改对象。

Like this:

public class B extends A { private int b; public B() { super(0); } @Override public int getA() { return b++; } }

Technically, you're not modifying the fields inherited from A, but in an immutable object, repeated invocations of the same getter are of course expected to produce the same number, which is not the case here.

Of course, if you stick to rule #1, you're not allowed to create this override. However, you cannot be certain that other people will obey that rule. If one of your methods takes an A as a parameter and calls getA() on it, someone else may create the class B as above and pass an instance of it to your method; then, your method will, without knowing it, modify the object.

更多推荐

本文发布于:2023-08-04 11:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1415161.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:final   java   immutable   Question

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!