2017-03-23 115 views
2

我有一个实体类的层次结构,并希望在Java中为它们创建服务接口的层次结构。那么UI组件应通过接口来访问实体相关的服务:Java通用接口层次结构

class BaseEntity { } 
class Fruit extends BaseEntity { } 
class Banana extends Fruit { } 
class Apple extends Fruit { } 

(这是在稍有不同的上下文中重用在多个地方)的UI组件需要通过接口FruitService访问果品服务,我要决定在运行期间,这将是BananaService或AppleService服务接口。我想这将是简单的使用泛型:

interface Service<T extends BaseEntity> 
{ 
    List<T> getAll(); 
    void save (T object); 
    void delete (T object); 
} 

// More strict interface only allowed for fruits. Referenced by UI component 
interface FruitService<F extends Fruit> extends Service<Fruit> {} 

// Interface only allowed for bananas 
interface BananaService extends FruitService<Banana> {} 

class BananaServiceImpl implements BananaService 
{ 
    // Compiler error here because expecting Fruit type: 
    @Override 
    public List<Banana> getAll() 
    { 
    } 
    ... 
} 

但是,这是给我下面的编译器错误:

The return type is incompatible with Service<Fruit>.getAll() 

为什么Java的不承认,执行已参数化香蕉?我希望BananaServiceImpl中的泛型参数能够像香蕉服务中指定的那样被解析为香蕉!

回答

8
interface FruitService<F extends Fruit> extends Service<Fruit> {} 

应该

interface FruitService<F extends Fruit> extends Service<F> {} 

这样一来,你在通用穿越到服务

+0

美丽,这个固定的编译错误。谢谢! – Wombat