3
First I would like to say that my doubt is not specifically about "verify that a generic object passed as parameter is subclass of an abstract class.", but I couldn’t pick a better title. If you find a better phrase, feel free to change.
Well, my situation is this, I have an interface GerenciarClientes
,that specifies operations to manage customers, an abstract class AbstractCliente
containing parameters default that every subclass of her should have, and an abstract class AbstractGerenciadorClientes
implementing GerenciarClientes
and has an abstract method:
Managerial:
public interface GerenciarClientes{
void adicionar(Object cliente);
void remover(Object cliente);
void editar(Object cliente);
}
Abstract client:
public abstract class AbstractCliente{
protected int codigo;
public AbstractClient(int codigo){
this.codigo = codigo;
}
}
Abstractmanager:
public class AbstractGerenciador implements GerenciarClientes{
/* Construtor */
@Override
void adicionar(Object cliente);
@Override
void remover(Object cliente);
@Override
void editar(Object cliente);
protected abstract boolean verificaDadosCliente(Object cliente);
}
My problem is this: When I create the class MeuGerenciador
, extending AbstractGerenciadorCliente
i am obliged to implement the method verificaDadosCliente(Object cliente)
and pass an object as a parameter. In this case, I would like the object to be a subclass of AbstractCliente
( suppose the name of the subclass is MeuCliente
). In class AbstractCliente
I changed the abstract method parameter to Class<? extends AbstractCliente> cliente
, but the problem is that when I do this, I can’t perform Typecast for class MeuCliente
protected abstract boolean verificaDadosCliente(Class< ? extends AbstractCliente> cliente){
MeuCliente c = (MeuCliente) cliente; // ERRO
}
- How can I fix this error?
- If the ideal is to keep the original signature (passing
Object cliente
) how can I verify that the object extendsAbstractCliente
? - Every time I give override in the abstract method I have to do Typecast within the method? Or have some way to do it automatically?
Declare the method as
verificaDadosCliente(AbstractCliente cliente)
does not solve? Then you call him passing the object of typeMeuCliente
as a parameter, which will work because it is also aAbstractCliente
.– Piovezan
@Piovezan The problem is that
MeuCliente
can own methods, therefore it would not be possible to access them usingAbstractCliente
– regmoraes
@but if you NEED the methods in
MeuCliente
, no use trying to do generic like that. You would have to useverificaDadosCliente(MeuCliente cliente)
, since it is not any instance ofAbstractCliente
that will work.– hartungstenio