1

Consider the below scenario:

String title;

    public Dummy_3(String title) {
        this.title = title;
    }


public String getTitle() {
        return title;
    }

In the main method, even if I use clone() or =, the results are the same. Can someone explain?.

Using =:

public static void main(String[] args) {

        Dummy_3 obj1 = new Dummy_3("Avengers: Infinity War");
        Dummy_3 obj2 = new Dummy_3("Avengers: Endgame");
        System.out.println(obj1.getTitle());
        System.out.println(obj2.getTitle());
        obj1 = obj2;
        System.out.println(obj1.getTitle());
        System.out.println(obj2.getTitle());
    }

Using clone():

public static void main(String[] args) {

        Dummy_3 obj1 = new Dummy_3("Batman Begins");
        Dummy_3 obj2 = new Dummy_3("Batman: The Dark Knight");
        System.out.println(obj1.getTitle());
        System.out.println(obj2.getTitle());
        obj2 = obj1.clone();
        System.out.println(obj1.getTitle());
        System.out.println(obj2.getTitle());

    }

Note: I know that there is a duplicate question, but the answer is not clear for me. Appreciate it if anyone can explain. Question

  • Add a title setter to your Dummy_3 class, and set the title of obj1 after the equals and the clone but before the println statements. – Gilbert Le Blanc Oct 19 '21 at 04:59
  • Also see [How do I copy an object in Java?](https://stackoverflow.com/questions/869033/how-do-i-copy-an-object-in-java) – Charlie Armstrong Oct 19 '21 at 05:08
  • I'm sorry, Gilbert. I think we are deviating from the original question. To answer, whatever the title we've set for the obj1, will be printed for both the objects obj1 & obj2 as they're pointing to the same reference. – Surendra Anand Oct 19 '21 at 05:10
  • 2
    Using `obj2 = obj1;`, both variables point to the same object. Using `obj2 = obj1.clone();`, the two variables point to different objects with the same value of properties. Without `clone()`, if you change the value of properties in `obj1` afterwards, the value of properties in `obj2` also change, which doesn't happen with `clone()`. – Ricky Mo Oct 19 '21 at 05:13
  • Thanks, Ricky... That's the exact answer I was looking for. Appreciate it. – Surendra Anand Oct 19 '21 at 07:08

0 Answers0