Search code examples
javaoopobject-reference

Unexpected output on re-assigning an object-reference


I am learning OOP, and got some assignment on making object-references and checking results. I got a Book class and a BookTest class, where in the BookTest class I make 4 object references to the Book object.

A Book has a name, and a function to get that name of that book.

class Book {
    private String name;

    public Book(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}

The references to the Book object looks like this:

Book b1 = new Book("The story of ...");
Book b2 = b1;
Book b3 = new Book("Second story");
Book b4 = new Book("Third story");

This all works great, whenever I print out b2.getName() I get the expected "The story of ..." string.

But whenever I add this this line before the printing of b2.getName() line:

b1 = b3;

I expected b2.getName() to be "Second story", because b1 has been assigned to b3. It is in-fact still the "The story of ..." string.

Why is this?


Solution

  • Book b1 = new Book("The story of ...");
    Book b2 = b1;
    Book b3 = new Book("Second story");
    Book b4 = new Book("Third story");
    

    enter image description here

    After b1 = b3; the b1 reference goes to the b3 but not the b2.

    enter image description here

    I hope this helpful to understand.