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());- A. 2
- B. 1
- C. Compilation error: hashCode cannot be overridden without equals
- 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
- What is printed? java class Base { Base self() { return this; } } class Derived extends Base { @Override Derived self() { return this; }…
- What is printed? java class Account { private double balance; Account(double b) { balance = b; } void withdraw(double amt) { if (amt >…
- What is printed? java class Task { void execute() throws Exception { try { riskyStep(); } catch (RuntimeException e) { throw new…
- What is printed? cpp class Base { public: virtual void op() { cout << "Base::op "; } void callOp() { this->op(); } }; class Derived…
- What is printed? cpp struct Base { virtual std::string name() const { return "Base"; } }; struct Derived : Base { std::string name() const…
- What is printed? java class Resource { String name; Resource(String n) { name = n; } @Override protected void finalize() {…