Interface defining the signature in a generic way of the methods to be implemented

Asked

Viewed 838 times

3

I own three classes:

  1. Repositoriosolicitant
  2. Repositoriomotorist
  3. Repositorioviagem

All have the following methods with the exception of Repositorioviagem which does not have "Change". The Object can refer to the classes Driver, Requester and Travel.

  1. Add void
  2. Remove void
  3. Change Boolean
  4. Seek Object
  5. Exhibited void
  6. Arraylist searches

I would like to know how to implement a single Interface for the 3 Repositories with the above methods in a generic way, so I can use any class I pass. Whether Add with Requester, Driver or Travel.

1 answer

4


You can use a generic type on 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 some class (let’s say Repositorio you just need to change the interface statement to:

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

EDIT

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

throw new UnsupportedOperationException("Não suportado.");
  • 1

    Wow, created the class with the same name I was creating :p Just a detail, don’t need public and it is worth adding that the class RepositorioViagem will have to implement everything, regardless whether to use the method or not alterar.

  • @diegofm I was doubtful in changing too, will be that the best way is to create 2 interfaces?

  • 1

    No, just don’t implement, leave the method empty, or launch a UnsupportedOperationException within the method should any unsuspecting attempt to implement

  • 1

    She’d be empty anyway.

  • my doubt was more about the shape that would be "typed", I believe that the lack of <T> in the interface name bugged every time I used T in the methods.

  • @Diego it is interesting to put the part of public and Exception in response?

  • 2

    @Sorack look, the exception part I find valid as suggestion, now the modifier, I never used, but I was in doubt if it is dispensable even.

  • @diegofm the modifier can be protected so you can specify

  • 2

    @sorack, you may not, all interface methods are obligatorily public, so the IDE does not complain about the public, but neither does it complain if it does not add it. protected from syntax error.

  • 1

    @diegofm true... so I didn’t even need to specify it anyway

Show 5 more comments

Browser other questions tagged

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