2016-02-01 41 views
-4

在下面的代碼中,在位置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

我認爲你需要@Override克隆方法,因爲它默認使用Object類,每個類都是 –

+0

的擴展。在Truck的克隆方法中,使用'Truck result = super.clone();'和'result。 y = y;' – FredK

+0

@FredK'Truck result = super.clone();'爲什麼要編譯? – Tom

回答

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(); 
    } 
}