Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java interfaces - parametric polymorphism

In Java what's the "correct" way to implement an interface where the parameters for a method need parametric polymorphism?

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?

like image 330
Bob Avatar asked Jul 18 '26 17:07

Bob


1 Answers

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) { ... }
}
like image 100
jjnguy Avatar answered Jul 21 '26 05:07

jjnguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!