Use of equals and inheritance

3

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;
        }
    }
    
asked by anonymous 21.11.2014 / 04:36

1 answer

2

This is a typical use case for super :

  • Compare the instances using the superclass criteria;
  • If all is ok, compare also using the criteria of the class itself.
  • 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.

        
    21.11.2014 / 07:53