ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Base {
    public int hashCode() { return 1; }
}
class Derived extends Base {
    @Override
    public int hashCode() { return super.hashCode() + 1; }
}
// in main:
System.out.println(new Derived().hashCode());
  1. A. 2
  2. B. 1
  3. C. Compilation error: hashCode cannot be overridden without equals
  4. D. 0

Correct answer: A. 2

Java allows overriding hashCode() alone (though best practice pairs it with equals()); Derived's override calls super.hashCode() (Base's, returning 1) and adds 1, giving 2 — no compile-time requirement forces equals() to be overridden alongside it.

More OOP with C++ and Java questions

Exams that ask this topic