tags:

views:

70

answers:

2

Trying to do something like:

public interface Order {      
    public List<? extends OrderItem> getItems();  
    public void setItems(List<? extends OrderItem> items);  
}  

public interface OrderItem {  
  // stuff
}  

public calss OrderItemImp implements OrderItem {  
  // stuff
}  

public class OrderImp implements Order {  
    public List<OrderItemImp> getItems() {  
        return items;  
    }  
    public void setItems(List<OrderItemImp> items) {  
        this.items = items;  

    }  
}

Compiler complaining about setItems method. How can I make this work? Thanks.

+1  A: 

try replacing

public void setItems(List<? extends OrderItem> items);

with

public <T> void setItems(List<T extends OrderItem> items);

. This is now a generic method

Atmocreations
And the implementation in `OrderImp` should be `setItems(List<T extends OrderItem>)` as well. There is no (easy) way to ensure the items are actually `OrderItemImp` and not some other implementation of `OrderItem`.
Daniel Pryden
Your syntax is not quite right, it should be `public <T extends OrderItem> void setItems(List<T> items);`
Lachlan
+3  A: 

In your Order interface definition, the methods look like a pair of get/set methods i.e. logically a property. In which case they need to have the same type. You need to tie them together via a named type parameter:

public interface Order<T extends OrderItem> {      
    public List<T> getItems();  
    public void setItems(List<T> items);  
}

Not entirely sure if this is the right syntax in Java, but basically both methods must end up referring to the exact same type.

Daniel Earwicker
And `public class OrderImp implements Order<OrderItem> {` .
Tom Hawtin - tackline
Perfect! Thank you
Fedor