-2

我正在尝试复制我已经创建的 BookOrder,但是,它没有正确创建。到目前为止,我有这个。

public class BookOrder
{
    private String author;      
    private String title;
    private int quantity;
    private double costPerBook;
    private String orderDate;
    private double weight;
    private char type;      //R,O,F,U,N

    public BookOrder (String author, String title)
    {
    }

    public BookOrder(String author, String title, int quantity, double costPerBook, String orderDate, double weight, char type)
    {
        this.author= author;
        this.title= title;
        this.quantity= quantity;
        this.costPerBook= costPerBook;
        this.orderDate= orderDate;
        this.weight= weight;
        this.type=type;
    }

    public BookOrder(BookOrder bookOrder)
    {
    }

但是,当我尝试在此处复制时:

public class TestBookOrder
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);

        Utility.myInfo("11/5,2013", "Project4");
        Utility.pressEnterToContinue();
        Utility.clearScreen();

        BookOrder BookOrder1 = new BookOrder("Jonathan", "Book1", 12, 6.75, "11/5/2013", 8.75, 'r');
        System.out.print(""+ BookOrder1.invoice());

        BookOrder copyA = new BookOrder(BookOrder1);

        BookOrder copyB= new BookOrder(BookOrder1);

        copyB.adjustQuantity(-5);

        System.out.print("\n"+ copyB.invoice());
        System.out.print("\n"+ copyA.invoice());

    }
}

它只是将 copyA 和 copyB 的发票返回为 null 和 0。任何人都知道 copy 方法中需要包含哪些代码?

4

3 回答 3

1

为了使这项工作,您需要更改以下代码。这将创建一个新对象,并将填充作为输入传递的 BookOrder 值。希望这能回答你的疑问。

public BookOrder(BookOrder bookOrder)
    {
    this.author= bookOrder.getAuthor();
    this.title= bookOrder.getTitle();
    this.quantity= bookOrder.getQuantity();
    this.costPerBook= bookOrder.getCostPerBook();
    this.orderDate= bookOrder.getOrderDate();
    this.weight= bookOrder.getWeight();
    this.type=bookOrder.getType();
    }
于 2013-11-06T06:41:10.030 回答
0

您需要将参数 BookOrder 的值复制到当前参数中。

例如,

class Foo {
  private int bar;

  public Foo(Foo foo) {
    this.bar = foo.bar;
    // same for other fields if they exist.
  }
}

顺便说一句,您将要解决此问题:

public BookOrder (String author, String title)
{
}

您正在丢弃传递给此构造函数的参数,完全忽略它们。

编辑:这已经在之前对同一作业的上一个问题的回答中向您解释过!

于 2013-11-06T06:41:11.780 回答
0

那是因为您需要在复制构造函数中将传递对象中的所有字段分配给当前对象。

public BookOrder(BookOrder bookOrder) {
    this.author = bookOrder.getAuthor(); // since they are private and thus you need getter to get the values
    this.title = bookOrder.getTitle();
    this.quantity = bookOrder.getQuantity();
    this.costPerBook = bookOrder.getCostPerBook();
    this.orderDate = bookOrder.getOrderDate();
    this.weight = bookOrder.getWeight();
    this.type =bookOrder.getType();
}
于 2013-11-06T06:41:38.413 回答