This question already has answers here:
Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?
                                
                                    (17个答案)
                                
                        
                5年前关闭。
            
        

我对泛型有疑问。

我定义了基类ServiceObjectServiceObjectsList

class ServiceObject {};
class ServiceObjectsList<T extends ServiceObject> extends ArrayList<T> {};


然后,我定义了一些后代类:

class UserServiceObject extends ServiceObject {};
class UserServiceObjectsList extends ServiceObjectsList<UserServiceObject> {};

class ItemServiceObject extends ServiceObject {};
class ItemServiceObjectsList extends ServiceObjectsList<ItemServiceObject> {};

// etc...


现在,我需要将UserServiceObjectsList视为ServiceObjectsList<ServiceObject>

如果我写:

ServiceObjectsList displayableServiceObjects;


那么我就无法遍历它们:

for (ServiceObject serviceObject : displayableServiceObjects)


引发错误“不兼容的类型”。

如果我写ServiceObjectsList<ServiceObject> displayableServiceObjects
那么我无法分配UserServiceObjects

displayableServiceObjects = new UserServiceObjects();


它会引发完全相同的“不兼容类型”错误;

我做错了什么?

所有ServiceObjectServiceObjectsList及其后代确实需要。然后封装一些功能。

最佳答案

您应该在声明中指定通用类型:

ServiceObjectsList<? extends ServiceObject> displayableServiceObjects;


并且“不兼容的类型”错误将消失。

10-02 11:09