Given:
class Shape { String name;/*from w w w .j av a 2s . c om*/ Shape(String n) { name = n; } } class Rectangle extends Shape { public boolean equals(Object o) { Rectangle n = (Rectangle) o; if (name.equals(n.name)) return true; return false; } public int hashCode() { return name.length(); } Rectangle(String s) { super(s); } } public class Main extends Rectangle { public static void main(String[] args) { Shape n1 = new Shape("bob"); Shape n2 = new Shape("bob"); Rectangle a1 = new Rectangle("fred"); Rectangle a2 = new Rectangle("fred"); Main s1 = new Main("jill"); Main s2 = new Main("jill"); System.out.print(n1.equals(n2) + " " + (n1 == n2) + " | "); System.out.print(a1.equals(a2) + " " + (a1 == a2) + " | "); System.out.println(s1.equals(s2) + " " + (s1 == s2)); } Main(String s) { super(s); } }
What is the result?
D is correct.
Shape uses the default equals()
method that returns true only when comparing two references to the same object.
Rectangle overrides equals()
(and Main inherits the overridden method) and uses the name variable to determine equality.
The == operator ALWAYS compares to see whether two reference variables refer to the same object.