Interface that defines the generic signature of the methods to be implemented

3

I have three classes:

  • Request Repository
  • RepositoryMotorist
  • RepositoryTravel
  • All have the following methods with the exception of RepositorioTravel which does not have the "Change". The Object can refer to the Driver, Applicant, and Travel classes.

  • Add void
  • Remove void
  • Change boolean
  • Find Object
  • View all void
  • SearchAll ArrayList
  • I would like to know how to implement a single Interface for the 3 Repositories with the methods above in a generic way, so I can use any class I pass. Be added with Requester, Driver or Trip.

        
    asked by anonymous 28.11.2016 / 18:22

    1 answer

    4

    You can use a generic type in interface as follows:

    import java.util.ArrayList;
    
    public interface ICRUD<T> {
      void adicionar(T objeto);
      void remover(T objeto);
      boolean alterar(T objeto);
      T buscar(int id);
      void exibirTodos();
      ArrayList<T> buscarTodos();
    }
    

    And use it, for example, as follows:

    import java.util.ArrayList;
    
    public class CRUDRepositorioSolicitante implements ICRUD<RepositorioSolicitante>{...}
    

    If you want to force objects to be inherited from a class (let's say it is Repositorio you just need to change the interface declaration to:

    public interface ICRUD<T extends Repositorio> {...}
    

    EDIT

    In the case of the class that will not have method alterar you can throw the following exception:

    throw new UnsupportedOperationException("Não suportado.");
    
        
    28.11.2016 / 18:32