Constructors to create BookCopy and copy of a BookCopy

See below for my code and question about constructors for creating BookCopy and copy of a BookCopy.

public class Book {
  private String title;
   
  // Constructor
  public Book(String title) {
    this.title = title;
  }

  // Getter
  public getTitle() {
    return title;
  }

}
public class BookCopy {
  private Book book;
 
  // Constructor for creating a BookCopy of Book
  public BookCopy(Book book) {
    this.book = book;
    System.out.println("New BookCopy with title: " + book.getTitle());
  }
 
  // Constructor for creating a copy of a BookCopy
  public BookCopy(BookCopy bookCopy) {
    this.book = bookCopy.book; // Question: this rule doesn't work for making a copy of a BookCopy, how to do?
    System.out.println("Copy of BookCopy with title: " + bookcopy.getTitle());
  }

  // Getter
  public getTitle() {
    return book.getTitle();
  }
 
}

hm, thank for this post

It was a while ago this was posted, but it is a common enough problem in Java that it’s worth answering.

Java refers to objects by reference, that is, their memory address. If you define a Book book it will be given a new memory address. But creating a BookCopy and passing the book into it will not create a copy of the original book. It will just use the exact same memory reference.

Creating the constructor below does not help, because it makes a new reference to the new BookCopy, which has a reference to the passed in BookCopy, which then has a reference to the original book.

public BookCopy(BookCopy bookCopy) {
    this.book = bookCopy.book;
}

This code won’t compile unless you make BookCopy extend Book. Although, if you remove the 2nd constructor from BookCopy it will. The way you have it set up is actually similar to the Decorater design pattern.

Java has a few clone() methods, but they are kinda bug-prone. The best way to copy an object is to specifically use the “new” keyword.

Book book = new Book("Title")
Book bookCopy = new Book("WhateverPlaceholderTitleYouWant");

bookCopy = book;

Now both book and bookCopy are separate but equal Book objects.

1 Like