我有一個類,其中包含一個我重寫的內部類。這似乎工作正常。Casting List <>覆蓋Java中的內部類
class Car {
public static class CarItems
{
public void doStuff(){ ... }
}
}
class Honda extends Car {
public static class CarItems extends Car.CarItems
{
@Override
public void doStuff(){ ... }
}
}
問題
那車類是另一個類,我也重寫裏面:
class Dealership {
//
// #1: Here's a list of stuff, which includes car items
// as defined in parent class
//
protected List<CarAndStuff> carsAndStuff;
public static class CarsAndStuff {
private List<CarItems> carItems;
private String name;
// ...
//
// #2: This only returns the items from the rest of the
// clutter in this class
//
public List<CarItems> getCarsItems() { return carsItems; }
}
// As defined above
public static class CarItems { ... }
}
class HondaDealership extends Dealership {
//
// #3: This sub-class only cares about the items
//
protected List<CarItems> carItems;
public void extractItemsFromParent() {
List<CarItems> _items = new ArrayList<CarItems>();
for(CarsAndStuff stuff : carsAndStuff) {
//
// #4: So I try to extract the items, but using my
// overriden method. ERROR!
//
carItems.addAll(carsAndStuff.getCarItems());
}
this.carItems = carItems;
}
// As defined above
public static class CarItems extends Car.CarItems { ... }
}
但願這不是太多的代碼可循的,這一切都非常直截了當...我得到的錯誤是#4
Java試圖從Car.CarItems投射到Honda.CarItems。它說:
The method addAll(Collection<? extends Honda.CarItems>)
in the type List<Honda.CarItems>
is not applicable for the arguments (List<Car.CarItems>)
如果Honda.CarItems IS-A Car.CarItems,爲什麼不會是讓我一個列表添加到列表?
「這一切都非常簡單」......並非如此。 –
在你的代碼中,你正試圖將'List'添加到'List '中。你不能這樣做,因爲'Car.CarItems'不一定是'Honda.CarItems',最具體的說,'Car.CarItems'不會擴展'Honda.CarItems',反之亦然。 –
LJ2