3
I stopped in an exercise of a book I’m reading and in this shows an example of overloading the method equals
, I even understood the concept that he compares the reference between two objects, but in the method: public boolean equals(Object obj)
things started to get a little confusing.
My doubts are:
- What means this return of the method
equals
:return (getConta() == ((ExemploContaEquals) obj).getConta());
Why the
if
of the main method compares only the last two attributes of the instantiated objects? That is, only compares the numbers 20 and 21 of the objectsobj1
andobj2
respectively and the numbers 50 and 50 of the objectsobj3
andobj4
. What’s the difference then of having two attributes?package modulo04.Overload equals;
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");
}
}
}
So the two parameters are for if I have another attribute? So this(0.0) in the second constructor? now I realize I think that’s what confused me.
– Marcelo T. Cortes
As I put it, the author wanted to create a very didactic example, trying to elaborate a little and listing some good coding practices. The
this(0,0)
is to create an object with the agency and nonnull account values, since there is no methodset
for the attributeconta
.– Weslley Tavares