0

我已经使用 Java 在浅层克隆中创建了一个对象的克隆引用。但是当我更新对象时,存储在引用克隆中的字符串不会更新。为什么?基类是,

public class Base {
String name;
int price;


public Base(String a, int b) {
    name = a;
    price = b;
    System.out.println("The " + name + " is " + price + " rupees.");
}

public Base(Base ref) {
    this.name = ref.name;
    this.price = ref.price;
}}

具有 main 方法的类是,

public class ShallowCloning {
String name;
int price;
Base ref;   

public ShallowCloning(String a, int b, Base c) {
    name = a;
    price = b;
    ref = c;
}

public ShallowCloning (ShallowCloning once) {
    this.name = once.name;
    this.price = once.price;
    this.ref = once.ref;
    System.out.println("The " + name + " is " + price + " rupees.");
}

public static void main(String args[]) {
    Base pet = new Base("fennec fox", 8000);
    ShallowCloning obj = new ShallowCloning("Sugar glider", 5000, pet);
    ShallowCloning clone = new ShallowCloning(obj);
    System.out.println(obj.name);
    obj.name = "Dog";
    System.out.println(obj.name);
    System.out.println(clone.name);    //Still getting the previously assigned string.
    System.out.println(obj.ref);
    System.out.println(clone.ref);
}}

有什么方法可以更改我的代码以在此过程中获取更新的值?

4

0 回答 0