我有一个带有内部类的类,我可以重写它。这似乎很好。

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转换为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?

最佳答案

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

// 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(){ ... }
  }
}

10-06 01:35