带有可变实例变量的JavaSE6 Clone类

时间:2015-11-16 08:26:33

标签: java

我在这里做错了什么?从Murach的Java SE6自学Java。在实施可克隆接口的练习上工作。当我运行使用这些类的main()的应用程序时,我收到此错误。

线程“main”中的异常java.lang.ClassCastException:LineItem无法强制转换为Product     在LineItem.clone(LineItem.java:73)     在LineItemCloneApp.main(LineItemCloneApp.java:23) C:\ Users \ Jermell \ AppData \ Local \ NetBeans \ Cache \ 8.1 \ executor-snippets \ run.xml:53:Java返回:1 BUILD FAILED(总时间:0秒)

//****LineItem.java*********
public class LineItem implements Cloneable
{
    private Product product;
private int quantity;
private double total;

// constructor and a bunch of get and set methods

    public Object clone() throws CloneNotSupportedException
    {
        // special clone process to deal with mutable instant variable Product
        LineItem li = (LineItem) super.clone();
        Product p = (Product) this.getProduct().clone();
        li.setProduct(p);
        return li;            
    }
}

****** Differt .jave文件位于同一目录*******

//*****Product.java*******
public class Product implements Cloneable
{
    private String code;
    private String description;
    private double price;

    // constructor and a bunch of get and set methods

public Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}

0 个答案:

没有答案