What would be the result of compiling and running the following program?.
final class MyClass { Integer size;/*from w w w .j ava2s . co m*/ MyClass(Integer size) { this.size = size; } public boolean equals(MyClass obj2) { if (this == obj2) return true; return this.size.equals(obj2.size); } } public class Main { public static void main(String[] args) { MyClass objA = new MyClass(10); MyClass objB = new MyClass(10); Object objC = objA; System.out.println("|" + objA.equals(objB) + "|" + objC.equals(objB) + "|"); } }
Select the one correct answer.
(d)
Note that the method equals()
in the class MyClass overloads the method with the same name in the Object class.
Calls to overloaded methods are resolved at compile-time.
Using the reference objA
of the type MyClass results in the equals()
method of the MyClass to be executed,
and using the reference objC
of the type Object results in the equals()
method of the Object class to be executed.
This is a canonical example where using the @Override annotation in front of the equals()
method would be very useful.