0

I have created a cloned reference of an object in shallow cloning using Java. But when I update the object, the string stored in the referenced clone is not updated. why? The base class is,

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;
}}

The class with main method is,

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);
}}

Is there any way of altering my code to get updated values in this process?

Pon Samuel
  • 11
  • 1
  • The clone isn't the same object any more. If you want `clone` to be the same as `obj`, simply use `clone = object;`. – Andy Turner Dec 29 '17 at 08:48
  • I think you misunderstand the purpose of cloning (namely: Creating a **new** but identical instance of an object). If you want all changes to reflect to the other object as well, cloning is not the way to go. – OH GOD SPIDERS Dec 29 '17 at 08:48
  • If I code as, ShallowCloning clone = obj; I can still reflect the changes occurring in both the objects. – Pon Samuel Dec 29 '17 at 08:53

0 Answers0