ProgrammingVery hardProduct company OA

What is printed?

What is printed?
class Base {
    protected int code = 1;
}
class Derived extends Base {
    int code = 2;
}
// in main:
Base b = new Derived();
System.out.println(b.code);
  1. A. 2
  2. B. 1
  3. C. Compilation error: duplicate field code
  4. D. Runtime error

Correct answer: B. 1

Since fields are not polymorphic, accessing b.code uses the STATIC type of the reference (Base) to decide which field is accessed, regardless of the actual object's runtime type. It prints Base's own code, 1, not Derived's shadowing field 2.

More OOP with C++ and Java questions

Exams that ask this topic