KaiquanMah's picture
this == obj; OR Class1 var1 = (Class1) obj1; (x == obj1.x && y == obj1.y);
cc4c404 verified
raw
history blame
3.01 kB
We have previously used the equals method to compare String objects.
It is also possible to implement the method in own class.
This enables the COMPARISON of 2 OBJECTS created out of OWN CLASS.
Let's implement the method to class 'Point', which models a point in 2-dimensional coordinate system.
Toteutetaan siis metodi equals luokkaan Piste, joka mallintaa pistettä kaksiulotteisessa koordinaatistossa:
class Point {
private int x;
private int y;
//CONSTRUCTOR
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
// If same object, must be equal
if (this == obj) {
return true;
}
// Jos other is null, must be false
if (obj == null) {
return false;
}
// If other is not Point, must be false
if (obj.getClass() != Point.class) {
return false;
}
// OTHERWISE IF
// 1 not the same object OR
// 2 not null -> good OR
// 3 not a Point class
// -> Cast the input 'obj' as a Point object
Point other = (Point) obj;
//THEN CHECK
// If x and y are equal, points are equal
return (x == other.x && y == other.y);
}
}
The implementation of the method (usually) follows the same structure.
Note that it's up to the programmer to decide when two objects should be equal: do ALL ATTRIBUTES need to be EQUAL OR ONLY SOME?
For example, we can decide that 2 Student objects are equal if they have
1 - the 'same student id' - as the rest of the attributes are not important
2 - (but then again, in some other case we may require that 'all attributes' have equal value for 'students' to be equal):
class Student extends Person {
// Name and email are inherited from Person
private String studentId;
private int credits;
public Student(String studentId, String name, String email, int credits) {
super(name, email);
this.studentId = studentId;
this.credits = credits;
}
@Override
public boolean equals(Object obj) {
// SAME OBJECCT
if (this == obj) {
return true;
}
// NOT NULL
if (obj == null) {
return false;
}
// not 'Student' class
if (obj.getClass() != Student.class) {
return false;
}
// SAME studentId
Student other = (Student) obj;
// Strings are compared with equals method
return studentId.equals(other.studentId);
}
}
A typical error is to forget to use the 'equals' method when comparing objects:
for example, String objects' equality must be checked with equals method instead of == operator.
Most editors provide a way to insert the equals method automatically,
plese refer to your editor's documentation (or google it - for example "visual studio code java equals".