public class Point {
int x;
int y;
public Point(int initialX, int initialY){
x = initialX;
y= initialY;
}
public boolean equals (Object o){
if (o instanceof Point){
Point other = (Point)o;
return (x == other.x && y == other.y);
}else{
return false;
}
}
}
We haev defined "equals" method for our class using "instanceof".
We define and use instances (or objects) of this class in the following scenarios. In each case, specify what is the output. (hint: there is no error in the code - focus on understanding how reference types work).
Scenario 1:
public static void main(String[] args){
Point p1 = new Point(7, 2);
Point p2 = new Point(7, 2);
Point p3 = p2;
System.out.println((p2==p3)) + " " + (p1 == p2));
}
Scenario 2:
public static void main(String[] args){
Point p1 = new Point(7, 2);
Point p2 = new Point(7, 2);
Point p3 = p2;
System.out.println(p2.equals(3) + " " + p1.equals(p2));
}
Scenario 1:
public static void main(String[] args){
Point p1 = new Point(7, 2); //A Point object p1 initialized
Point p2 = new Point(7, 2);//A Point object p2 initialized
Point p3 = p2; //Here Point p3 is given reference of Point P2
System.out.println((p2==p3)) + " " + (p1 == p2));
}
Therefore p2 and p3 has same reference,p2==p3 (true)
p2 and p1 do not have same reference,p2==p1 (false)
output : true false
Scenario 2:
public static void main(String[] args){
Point p1 = new Point(7, 2);
Point p2 = new Point(7, 2);
Point p3 = p2;
System.out.println(p2.equals(3) + " " + p1.equals(p2));
}
equal function checks object type and there element values.
if two objects are of same type and there corresponding values are
same,then equal() function will return true.
output : true true
Get Answers For Free
Most questions answered within 1 hours.