在图书订单中复制图书订单

时间:2013-11-06 06:38:42

标签: java

我正在尝试复制我已经创建的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.任何人都知道复制方法中需要什么代码?

3 个答案:

答案 0 :(得分:1)

要使其工作,您需要更改以下代码。这将创建一个新的Object,并将与作为输入传递的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();
    }

答案 1 :(得分: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)
{
}

你丢弃传递给这个构造函数的参数,完全忽略它们。

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

答案 2 :(得分: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();
}