Analyze the following code. // Program 1: public class Test { public static void main(String[] args) { Object a1 = new A(); Object a2 = new A(); System.out.println(a1.equals(a2)); } } class A { int x; public boolean equals(A a) { return this.x == a.x; } } // Program 2: public class Test { public static void main(String[] args) { A a1 = new A(); A a2 = new A(); System.out.println(a1.equals(a2)); } } class A { int x; public boolean equals(A a) { return this.x == a.x; } } A.

Analyze the following code.
// Program 1:
public class Test {
  public static void main(String[] args) {
    Object a1 = new A();
    Object a2 = new A();
    System.out.println(a1.equals(a2));
  }
}
class A {
  int x;
  public boolean equals(A a) {
    return this.x == a.x;
  }
}

// Program 2:
public class Test {
  public static void main(String[] args) {
    A a1 = new A();
    A a2 = new A();
    System.out.println(a1.equals(a2));
  }
}
class A {
  int x;
  public boolean equals(A a) {
    return this.x == a.x;
  }
}


A. Program 1 displays true and Program 2 displays true
B. Program 1 displays false and Program 2 displays true
C. Program 1 displays true and Program 2 displays false
D. Program 1 displays false and Program 2 displays false

The correct answer is B

Explanation: In Program 1, the equals method in the Object class is invoked. In Program 2, the equals method in the class A is invoked. There are now two overloaded methods available in the class A. i.e. public boolean equals(Object a) and public boolean equals(A a). Which of the two is used by a1.equals(a2) is determined at compilation time. a1.equals(a2) in Program 1 matches the equals method defined in Object and a1.equals(a2) in Program 2 matches the equals method defined in the class A.


Java

Learn More Multiple Choice Question :