Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface too general

Tags:

java

interface

In the Java code I'm working with we have an interface to define our Data Access Objects(DAO). Most of the methods take a parameter of a Data Transfer Object (DTO). The problem occurs when an implementation of the DAO needs to refer to a specific type of DTO. The method then needs to do a (to me completely unnecessary cast of the DTO to SpecificDTO. Not only that but the compiler can't enforce any type of type checking for specific implementations of the DAO which should only take as parameters their specifc types of DTOs. My question is: how do I fix this in the smallest possible manner?


1 Answers

You could use generics:

DAO<SpecificDTO> dao = new SpecificDAO();
dao.save(new SpecificDTO());
etc.

Your DAO class would look like:

interface DAO<T extends DTO> {
    void save(T);
}

class SpecificDAO implements DAO<SpecificDTO> {
    void save(SpecificDTO) {
        // implementation.
    }
    // etc.
}

SpecificDTO would extend or implement DTO.

like image 86
johnstok Avatar answered Dec 30 '25 10:12

johnstok