[英]immutable final arguments and returns
Can non-final arguments or returned objects make an object mutable? 非最终参数或返回的对象可以使对象可变吗?
What difference does it make by changing this: 通过更改以下内容有什么区别:
public final class MyImmutableClass {
public final MyObject doStuff(final SomeObject someObject) {
...
}
}
to this: 对此:
public final class MyImmutableClass {
public MyObject doStuff(SomeObject someObject) {
...
}
}
When the goal is to make MyImmutableClass
truly immutable. 当目标是使
MyImmutableClass
真正不可变时。
After appling the change, is MyImmutableClass
still considered immutable? 应用更改后,
MyImmutableClass
仍被视为不可变的? If not, what state could be altered by making the changes? 如果没有,可以通过更改来更改什么状态?
First of all a class is never immutable , an instance of a class could be. 首先,一个类永远是不可变的 ,一个类的实例可能是不可变的。 Next,
下一个,
public final MyObject doStuff(final SomeObject someObject) {
Here, you can't change the reference someObject
to point to some other instance of SomeObject
inside the method. 在这里,您不能将引用
someObject
更改为指向该方法内部SomeObject
其他实例。 This guarantees that you are always using the argument passed by the caller. 这样可以确保您始终使用调用方传递的参数。
Next, final
in a method signature ensures that it cannot be overridden (which is redundant if the class itself is marked as final
.) 接下来,方法签名中的
final
确保不能覆盖它(如果类本身被标记为final
,则这是多余的。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.