Polymorphism with Arraylist

Asked

Viewed 475 times

2

I have the Nterface below and I would like to know how to overlay the method by passing another object to List because I have 4 classes in my entity, for example the entity classes are cliente, colaborador, produto and serviço and the classes that implement the interface are ClienteDAO, ColaboradorDAO, ServicoDAO, ProdutoDAO follows also an example of these:

public interface ISalaoDAO {

    int save(Object object);
    int update(Object object);
    int remove(Long id);
     List<Cliente> findAll();

}

public class ClienteDAO implements ISalaoDAO{
private static final String SQL_FIND_ALL = 
            "select * from CLIENTE";
public List<Cliente> findAll() {
        Connection conn = DBConnection.getConnection();
        PreparedStatement pstm = null;
        List<Cliente> clientes = new ArrayList<Cliente>();
        ResultSet rs = null;
        try {
            pstm = conn.prepareStatement(SQL_FIND_ALL);
            rs = pstm.executeQuery();
            while(rs.next()){
                Cliente cliente = new Cliente();
                cliente.setId(rs.getLong("ID_CLIENTE"));
                cliente.setCliente(rs.getString("NOME_CLIENTE"));
                cliente.setEnderecoCliente(rs.getString("ENDERECO_CLIENTE"));
                cliente.setTelefoneCliente(rs.getString("TELEFONE_CLIENTE"));
                clientes.add(cliente);
            }
        } catch (SQLException e) {
            try{
                if(conn != null){
                    conn.setAutoCommit(false);
                    conn.rollback();
                }
            }catch(SQLException e1){
                e1.printStackTrace();

            }finally{
                DBConnection.close(conn, pstm, rs);
            }                   
        }   
        return clientes;
    }

1 answer

3

I’ve never tried to do and I don’t know if it violates the principle of Liskov’s replacement or anything, but I suggest the following:

public interface ISalaoDAO<T> {
    int save(T object);
    int update(T object);
    int remove(Long id);
    List<T> findAll();
}

Here you specify the type of T in the implementer class:

public class ClienteDAO implements ISalaoDAO<Cliente> {
    ...
    public List<Cliente> findAll() {
        ...
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.