开发者

Java interfaces - parametric polymorphism

In Java what's the "correct" way to implement an interface where the parameters for a method need parametric polymor开发者_运维技巧phism?

For example, my interface contains:

public int addItem(Object dto);

The interface is implemented by various classes but in each the dto parameter is one of various strongly typed objects such as planeDTO, trainDTO or automobileDTO.

For example, in my planeDAO class:

public int addItem(planeDTO dto) { ... }

Do I simply implement with the dto parameter as Object and then cast to the appropriate type?


If the DTOs all inhrerit from a common superclass or implement a common interface you can do:

// DTO is the common superclass/subclass
public interface Addable<E extends DTO> {

    public int addItem(E dto);

}

And your specific implementations can do:

public class PlaneImpl implements Addable<planeDTO> {
    public int addItem(planeDTO dto) { ... }
}

Or, you can simply define your interface to take in the interface/superclass:

// DTO is the common superclass/subclass
public interface Addable {

    public int addItem(DTO dto);

}

Edit:

What you may need to do is the following:

Create interface -

interface AddDto<E> {
    public int addItem(E dto);
}

And implement it in your DAOs.

class planeDAO implements AddDto<planeDTO> {
    public int addItem(planeDTO dto) { ... }
}


Why not use an interface which provides the functionality you need and not reference the concrete types?

public int addItem(ITransportationMode mode);

Where planeDTO, trainDTO and automobileDTO all implement ITransportationMode


Are you trying to reach for something like double dispatch? What is the behaviour which varies depending on the type of the argument?


You could also use generic methods:

public interface Addable{
   public <T extends DTO> int addItem(T dto){}
}

You can read more about generic methods at : http://download.oracle.com/javase/tutorial/extra/generics/methods.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜