Question :
I have a parent class and in it I have equals
and I have other child classes of this parent class and I want to override equals
to compare private attributes of those child classes but I also want to use equals
of my father to compare the attributes inherited by my daughters, how would I do that without having to rewrite everything?
public class Pai {
String nome;
@Override
public boolean equals(Object obj) {
Pai other = (Pai) obj;
return(this.nome.equals(other.nome);
}
}
public class Filha extends Pai {
int atributoEspecifico';
@Override
public boolean equals(Object obj) {
// como comparo aquele atributo do meu pai também?
Filha other = (Filha) obj;
return this.atributoEspecifico == other.atributoEspecifico;
}
}
Answer :
This is a typical use case for super
:
Code example (without handling errors, such as checking if the argument belongs to the right class):
public boolean equals(Object obj) {
if ( !super.equals(obj) )
return false;
Filha other = (Filha) obj;
return this.atributoEspecifico == other.atributoEspecifico;
}
Note that this works at any depth: if you create a Neta
class that inherits from Filha
, and call super.equals
in it too, the Pai
, Filha
, and Neta
, in that order.