gpt4 book ai didi

java - 为什么要使类成为final来创建不可变对象(immutable对象)

转载 作者:行者123 更新时间:2023-12-01 19:56:12 25 4
gpt4 key购买 nike

我正在尝试遵循下面的代码。我不太确定第 #5 行发生了什么以及为什么第 #7 行的语句将不可变类中 tmp 的值设置为 10?

public class HelloWorld{ 
public static void main(String []args){
child c = new child(4);
System.out.println(c.getTemp()); // line #4 prints 4
immutable i = (immutable) c; //line #5
System.out.println(i.getTemp()); // line #6 prints 4
c.setTemp(10); //line #7
System.out.println(i.getTemp()); // line 8 prints 10
}
}

class immutable{
private int tmp;
immutable(){
}
immutable(int val){
tmp = val;}
public int getTemp(){
return tmp; }
}

class child extends immutable{
private int tmp1;
child(){
}
child(int y){
super(y);
tmp1= y;
}
public int getTemp(){
return tmp1;}

public void setTemp(int y){
tmp1 = y;}
}

最佳答案

忽略此处的样式和约定错误,只关注您的问题。

如果您的类不是最终类,则子类可能会覆盖不变性。这是一个例子。

这是不可变类

public class Immutable {
private final int value;

public Immutable(int value) {
this.value = value;
}

public int getValue() {
return value;
}

}

“Immutable”类不是最终的,所以我可以扩展它。

public class Mutable extends Immutable {
private int newValue;

public Mutable(int value) {
super(value);

newValue = value;
}

public int getValue() {
return newValue;
}
public void setValue(int newValue) {
this.newValue = newValue;
}


}

现在进入主类,

public static void main(String[] arg){
Immutable immutable = createImmutableObject(10)
System.out.println(immutable.getValue()); //This prints 10
mutable.setValue(100);
System.out.println(immObj.getValue()); //This prints 100
}

private Immutable createImmutableObject(int val){
return new Mutable(val);
}

在 createImmutableObject 方法中,我返回 Immutable 类型的引用。因此,使用 API 的开发人员会假设返回的对象是不可变的。但是,该对象是 Mutable 类型(其状态可以更改),并且只是父类的引用。我可以更改返回对象的状态,这会破坏“不变性”

关于java - 为什么要使类成为final来创建不可变对象(immutable对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49663289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com