Java Reference
In-Depth Information
Let's look at an example. Suppose we have the following class named
Dog
:
1. public class Dog {
2. private String name;
3. private int age;
4.
5. public Dog(String name, int age) {
6. this.name = name;
7. this.age = age;
8. }
9. }
What does it mean for two
Dog
objects to be equal? Suppose in our application two
Dog
objects are equal if they have the same name and age. Then
Dog
can override
equals
and
implement this business logic:
1. public class Dog {
2. private String name;
3. private int age;
4.
5. public Dog(String name, int age) {
6. this.name = name;
7. this.age = age;
8. }
9.
10. public boolean equals(Object obj) {
11. if(!(obj instanceof Dog))
12. return false;
13. Dog other = (Dog) obj;
14. if(this.name.equals(other.name) &&
15. (this.age == other.age)) {
16. return true;
17. } else {
18. return false;
19. }
20. }
21. }
Within
equals
, we fi rst test to see if the class type of the other object is
Dog
. If the other
object is not a
Dog
object, we can quickly deduce the two objects are not equal. Otherwise,
the incoming reference is cast to a
Dog
reference and the
name
and
age
are checked for
equality. Because the
name
is a
String
object, we use the
equals
method of the
String
class
to compare the two
name
objects.
Search WWH ::
Custom Search