Use of equals and inheritance

Asked

Viewed 307 times

3

I have a parent class and in it I have a equals and I have other daughter classes of this father class and in them I want to overwrite the equals to compare particular attributes of these daughter classes but also want to make use of the 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;
        }
    }
  • You can put a passage that exemplifies this?

  • sure, I’ll post.

  • puts a stretch, for better understanding

  • You tried to compare the parent class attribute and it didn’t work? You tried return this.atributoEspecifico == other.atributoEspecifico && this.nome.equals(other.nome)? The nome is visible throughout the package, then it should be visible in the daughter unless the daughter is in another package. Tried to use proteceted in the nome? If you do this there if I’m not mistaken you’ll have to access with super.

  • 1

    @bigown I think the key point here is "without having to rewrite everything". Even if the nome is accessible in the subclass, it would not be a good idea to repeat the logic of equals if what the AP wants is to reuse it (in other cases it could be). P.S. I used the reference in your comment on the deleted reply in my reply.

1 answer

2

This is a typical use case for the super:

  1. Compare instances using superclass criteria;
  2. If everything is ok, compare also using the criteria of the class itself.

Code example (no error handling, 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 in any depth: if you create a class Neta who inherits from Filha, and call the super.equals the criteria of Pai, Filha and Neta, in that order.

Browser other questions tagged

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