Java collections covariance problem

前端 未结 3 1138
情话喂你
情话喂你 2020-12-03 18:04

Lets say we have a program which contains such classes:

public interface AbstractItem {
}
public SharpItem implements AbstractItem {
}
public BluntItem imple         


        
3条回答
  •  失恋的感觉
    2020-12-03 18:24

    Here are a couple of extra ideas. Leave everything the same, but use this:

    interface AbstractToolbox {
        public List getItems();
    }
    

    This basically says that the abstract class' items are an unknown type, but subclasses can make it concrete. This would require you to call getItems() on a reference of type ExpensiveToolbox or CheapToolbox to be able to retrieve a list that allows you to add items, etc.

    ExpensiveToolbox toolbox = new ExpensiveToolbox();
    AbstractToolbox absTB = toolbox;
    
    List items1 = absTB.getItems(); //fine
    List items2 = absTB.getItems(); //compile error
    List items3= toolbox.getItems(); //fine
    

    Alternatively, you could just type AbstractToolbox:

    public interface AbstractToolbox {
        public List getItems();
    }
    public ExpensiveToolbox implements AbstractToolbox {
        public List getItems() { //...
    }
    

提交回复
热议问题