gpt4 book ai didi

java - 强制转换 List<> 覆盖 Java 中的内部类

转载 作者:行者123 更新时间:2023-12-02 05:49:02 26 4
gpt4 key购买 nike

我有一个类,其中有一个我重写的内部类。看起来效果很好。

class Car {
public static class CarItems
{
public void doStuff(){ ... }
}
}

class Honda extends Car {
public static class CarItems extends Car.CarItems
{
@Override
public void doStuff(){ ... }
}
}

问题

该 Car 类位于我也重写的另一个类中:

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 转换为本田.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 是 Car.CarItems,为什么它不允许我将列表添加到列表中?

最佳答案

这可能不是世界上最好的答案,但可以完成工作:

// Instead of addAll, add each item from CarsAndStuff.getCarItems
List<CarItems> _items = new ArrayList<CarItems>();

for (CarsAndStuff stuff : carsAndStuff) {
List<Car.CarItems> _carItems = stuff.getCarItems());
for (CarItems _carItem: _carItems) {

// ** Can't cast Car.CarItems ==> Honda.CarItems? Copy it! **
_items.add(new CarItems(_carItem));

}
}

总之,无需从 Car.CarItems 强制转换(显式或隐式)到 Honda.CarItems,只需复制该对象,从而使其成为真正的 Honda.CarItems。这要求您的 Honda.CarItems 实现一个复制构造函数,这对您来说是一个额外的步骤:

class Honda extends Car {
public static class CarItems extends Car.CarItems
{

public CarItems(Car.CarItems items) {
this.property_1 = items.property_1;
this.property_2 = items.property_2;
this.property_3 = items.property_3;

// etc.
}

@Override
public void doStuff(){ ... }
}
}

关于java - 强制转换 List<> 覆盖 Java 中的内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23743741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com