As for the first doubt, you are correct.
Second:
Not necessarily. In Java the Equals
method always looks for (or at least should, it depends on the actual implementation) to find the most descriptive comparison. It may even in some cases compare the reference, when this is the most descriptive way of comparing objects. But at first the benchmark comparison is avoided where possible.
The best example is the strings comparison. Identical strings but in different addresses return true
when using Equals
but false
when using ==
(this is a bit more complicated than this because of interning , but this is another subject).
So for your specific case, it would even be the same thing. Unless the Equals
implementation specifies the Pessoa
class to change the default behavior.
By default Java, through class Object
where all other classes are derived directly or indirectly, has an implementation of Equals
that compares references.
But it would be appropriate for this class Pessoa
to override the default implementation with another that is more descriptive. It takes some key field (s) and compares them to determine if it is the same identity or not. These fields would need to form a unique key, meaning no other instance of the class could be the same as another.
Is there an implementation? Only you can see it, we can not see it. You have to see in this class whether there is this implementation and how it is proceeding.
No Anthony Acciolly's review above has a link to his blog a> with a good example of implementation using the CPF as the unique identifier of the person's identity. This is a good way to make Equals
of class Pessoa
more relevant. Note that it is not at all extremely wrong to compare references in this case. But it is not the most intuitive. The ideal is to make this comparison have its own semantics. Here's how he did the Equals
implementation for the class thinking about the object's various situations:
@Override
public boolean equals(Object obj) {
// Um objeto é sempre igual a ele mesmo
if (this == obj) {
return true;
}
// Um objeto nunca deve ser igual a null
if (obj == null) {
return false;
}
/* Uma pessoa só pode ser igual a outra pessoa.
* Caso uma pessoa possa ser igual a uma de suas subclasses
* use !(obj instanceof Pessoa)
*/
if (getClass() != obj.getClass()) {
return false;
}
// Converte a referencia para uma pessoa
final Pessoa other = (Pessoa) obj;
// Duas pessoas só podem ser comparadas se possuem CPF
if (this.cpf == null || other.cpf == null) {
return false;
}
// Duas pessoas são iguais se possuem o mesmo CPF
return this.cpf.equals(other.cpf);
}
I've placed it on GitHub for future reference.
See the implementation details on his blog (he kindly gave this example).
I'll talk about this in more detail in that answer . It is about C # and has some differences for Java, but there I explain this identity thing better. I also speak a little bit of identity here in this answer .