(Java) Write the missing equals method needed for the Point class shown on the screen to work with this program. The missing method would be added to the Point class.
class PointTestP3 {
public static void main(String[] args) {
Point p1 = new Point(5, 6);
Point p2 = new Point(5, 6);
System.out.println(p1.equals(p2)); // prints "true"
}
}
Here, the point class is not provided. But, it is easy to assume that it represents (x, y) point.
So, I have written the Point class as per me.
class Point {
private int x;
private int y;
Point() {
x = y = 0;
}
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
Point p = (Point) o;
if (x == p.x && y == p.y) {
return true;
}
return false;
}
}
You just need to change the member variables name as per your code if they are not x and y.
Now comes the equals() method. You can write it in 2 ways. First is, there is an equal method in the Object class so you can override it using @Override notation and this can be done as :
@Override
public boolean equals(Object o) {
Point p = (Point) o;
if (x == p.x && y == p.y) {
return true;
}
return false;
}
}
This is what I have mentioned in the above code I wrote in the point class. Here, in the default equals method, there is an Object passed and when we are overriding, we need to make the method signature as it is.
So, inside the method, I converted that object into Point object because I had passed the same object from the main().
To check whether 2 points are equal, we need to check both x and y are same. So, when you call this as p1.equals(p2); this means your p1 variable is passed via 'this' pointer. So, in the method I wrote x == p.x which means here x is referred as this.x and p is what we passed in parameter here it is p2. So, this means it checks p1.x == p2.x and if the result is true for both x and y, it returns true otherwise false.
If you find this little bit difficult or don't want to use @Override, you can do it in easier way as follows. Both are doing the same thing..:
public boolean equals(Point p) {
if (x == p.x && y == p.y) {
return true;
}
return false;
}
You can directly pass the point object which you will get in the function parameter and can compare it in the same way as above.
So, read both the methods along with the description and use the suitable one. Don't forget to apply the variable names as per your Point class.
I executed the code with both of these equals() method and the result being printed is "true".
Do comment if there is any query. Thank you. :)
Get Answers For Free
Most questions answered within 1 hours.