I stopped in an exercise of a book I'm reading and in this shows an example of overloading the equals
method, I even understood the concept that it compares the reference between two objects, but in the method: public boolean equals(Object obj)
things began to get a little confusing.
My questions are:
- What this method returns
equals
:return (getConta() == ((ExemploContaEquals) obj).getConta());
-
Why does
if
of the main method compare only the last two attributes of instantiated objects? That is, it only compares the numbers 20 and 21 of theobj1
andobj2
objects respectively and the numbers 50 and 50 of theobj3
andobj4
objects. What's the difference then having two attributes?package modulo04.EqualsBackup;
public class ExemploContaEquals { private int conta = 0; public ExemploContaEquals(int agencia, int conta){ this.conta = conta; } public ExemploContaEquals(){ this(0,0); } public int getConta(){ return conta; } public boolean equals(Object obj){ if(obj != null && obj instanceof ExemploContaEquals){ return (getConta() == ((ExemploContaEquals) obj).getConta()); } else { return false; } } }
package modulo04.SobrecargaEquals;
public class ExemploContaEqualsPrincipal {
public static void main(String[] args) {
ExemploContaEquals obj1 = new ExemploContaEquals(10,20);
ExemploContaEquals obj2 = new ExemploContaEquals(10,21);
if(obj1.equals(obj2)){
System.out.println("Contas iguais");
} else {
System.out.println("Conta diferentes");
}
ExemploContaEquals obj3 = new ExemploContaEquals(10, 50);
ExemploContaEquals obj4 = new ExemploContaEquals(20,50);
if(obj3.equals(obj4)){
System.out.println("Contas iguais");
} else {
System.out.println("Contas difentes");
}
}
}