I have seen many people getting misunderstood by java object references and their assignment. A common misconception is that whenever a reference variable is assigned another reference variable, it creates a new object. For example, suppose we have a Book class and we are trying to create its object.
Book someBook = new Book();
Book anotherBook = someBook;
Here the conception is two objects are created. But this is plain wrong. Only one object is created and two variables refer to it. Let us first understand what exactly happens when the statement Book someBook = new Book(); is executed.
- Book someBook creates a reference variable called someBook of type Book .
- new Book() actually creates the instance of the class.
So the whole statement
Book someBook = new Book(); actually means:
A new instance of class Book is created and it is assigned to the reference variable someBook of type Book.
This can be diagrammatically represented as follows.
Now the statement Book anotherBook = someBook does not create a new object. It just means “The object that is being referred by the variable someBook is also referred by this new reference variable anotherBook “.
This can be seen diagrammatically as follows.
Hope this article helps clear this common doubt.