ProgrammingVery hardProduct-company placement · Java
What is printed?
What is printed?
class Pt {
int x;
Pt(int x) { this.x = x; }
public boolean equals(Object o) { return o instanceof Pt && ((Pt) o).x == x; }
public int hashCode() { return x; }
}
class CPt extends Pt {
String c;
CPt(int x, String c) { super(x); this.c = c; }
public boolean equals(Object o) {
return o instanceof CPt && super.equals(o) && ((CPt) o).c.equals(c);
}
}
// in main:
Pt p = new Pt(1);
CPt q = new CPt(1, "red");
System.out.print(p.equals(q) + " " + q.equals(p));- A. true true
- B. false false
- C. true false
- D. false true
Correct answer: C. true false
A CPt is a Pt, so p.equals(q) only compares x (true); but p is not a CPt, so q.equals(p) is false. Adding a field in a subclass this way breaks the symmetry required by the equals contract.
More OOP with C++ and Java questions
- What is printed? java interface Greeter { String name(); default String greet() { return "Hi " + name(); } } class G implements Greeter {…
- Which line fails to compile? java abstract class Shape { abstract double area(); } // in main: Shape a = new Shape(); // L1 Shape b = new…
- Which lines fail to compile? java class P { void f() { } static void g() { } } class C extends P { static void f() { } // L1 void g() { }…
- Which line fails to compile? java class P { Number get() { return 1; } int size() { return 0; } } class C extends P { Integer get() {…
- What is printed? java class T { int n; { n += 5; } T() { this(1); n = 2; } T(int k) { n += k; } } // in main: System.out.print(new T().n);
- What is printed? java class A { public String toString() { return "A"; } } class B extends A { public String toString() { return "B" +…