在程序中找到错误

时间:2016-02-01 22:59:23

标签: java debugging

在下面的代码中,假设在位置A之前存在某种错误,但我似乎无法弄明白。是否与克隆方法有关?我只需要帮助找出错误的位置以及为什么我可以自己修复它。谢谢。

class Vehicle implements Cloneable {

   private int x;

   public Vehicle(int y) { x = y;}

   public Object clone() { 
      Object result = new Vehicle(this.x);
      // Location "A"
      return result;
   }
   // other methods omitted
}

class Truck extends Vehicle {

   private int y;

   public Truck(int z) { super(z); y = z;}

   public Object clone() {
      Object result = super.clone();
      // Location "B"
      ((Truck) result).y = this.y;  // throws ClassCastException
      return result;             
   }
   // other methods omitted
}

1 个答案:

答案 0 :(得分:0)

Truck.clone()拨打super.clone()时,返回的值为Vehicle,而不是Truck

两个选项:

  • super.clone()替换为new Truck(...)
  • 同时在super.clone()中使用Vehicle,因此创建的实际实例为Truck

我更喜欢第二种选择:

class Vehicle implements Cloneable {

    private int x;

    public Vehicle(int y) { x = y;}

    @Override
    public Vehicle clone() { 
        try {
            return (Vehicle)super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e); // Cannot happen
        }
    }
}
class Truck extends Vehicle {

    private int y;

    public Truck(int z) { super(z); y = z;}

    @Override
    public Truck clone() {
        return (Truck)super.clone();
    }
}