What is the output of the following JAVA program?
public class Good {
private int m;
public Good(int m) {
this.m = m;
}
public Boolean equals(Good n) {
return n.m == m;
}
public static void main(String args[]) {
Good m1 = new Good(22);
Good m2 = new Good(22);
Object s1 = new Good(22);
Object s2 = new Good(22);
System.out.println(m1.equals(m2));
System.out.println(s1.equals(s2));
System.out.println(m1.equals(s2));
System.out.println(s1.equals(m2));
}
Here, the class has a method
$equals(Good\ n)$
This method does not override the original $equals(Object)$ method of Java because the parameter type is $Good$, not $Object$.
For Line 1:
$m1.equals(m2)$
Here both are objects of class $Good$, so $equals(Good\ n)$ is called.
Both values are $22$, so output is
$True$
For Line 2:
$s1.equals(s2)$
Here $s1$ and $s2$ are declared as $Object$ type.
So, Java calls $Object$ class $equals()$ method, which compares references.
Since both are different objects, output is
$False$
For Line 3:
$m1.equals(s2)$
Here $s2$ is of type $Object$, so $equals(Good\ n)$ is not called.
It calls $equals(Object)$, so reference comparison is done.
Output is
$False$
For Line 4:
$s1.equals(m2)$
Here $s1$ is of type $Object$, so again $Object$ class $equals()$ method is called.
Output is
$False$
Therefore, output is:
$True,\ False,\ False,\ False$
Online Test Series, Information About Examination,
Syllabus, Notification
and More.
Online Test Series, Information About Examination,
Syllabus, Notification
and More.