Java Interfaces - Parametric Polymorphism

In Java, what is the “right” way to implement an interface where the parameters for a method require parametric polymorphism?

For example, my interface contains:

public int addItem(Object dto);

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

For example, in my planeDAO class:

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

Is it possible to simply implement with the dto parameter as Object, and then apply to the corresponding type?

+3
source share
4 answers

If the DTOs all enter 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) { ... }
}

, /:

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

    public int addItem(DTO dto);

}

Edit:

:

-

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

DAO.

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

, , ?

public int addItem(ITransportationMode mode);

planeDTO, trainDTO automobileDTO ITransportationMode

0

- ? ?

0

:

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

: http://download.oracle.com/javase/tutorial/extra/generics/methods.html

0

Source: https://habr.com/ru/post/1786930/